From Wikiversity
Jump to navigation Jump to search

Explanation[edit | edit source]

This serves to:

  1. Show beginning students how the "case" statement will be used to display code snippets to study and to copy/paste directly into MatLab
  2. Show intermediate students and editors how to write code with a "case" statement.

Code[edit | edit source]

%%%How to use a case statement%%%%
clc;clear all;close all; %Always begin with these statements
fprintf('This code is divided into 3 sections \n' );
%*fprintf* prints to command window. /n makes new line.
sectionNumber= input('Enter case you wish to run: ');
%*input* prompts user to input an integer (1, 2, 3, ...)
    %*switch* executes only case you select
    % each case should run as stand-alone code
    case 1
        fprintf('Case 1 adds x + y  \n');
        y = 3
    case 2
        fprintf('And,case 2 multiplies x * y \n');
        y = 3
    case 3        
        fprintf('And of course, case 3 divides x/y \n');
        y = 3
end % this ends *case*
fprintf('To run this code again type *caseStructure*\n' );
% this last line is in effect only if you name your file *caseStructure.m*