ITW7
ITW7
ITW7
Workshop
Loops and Conditional
Statements
if, elseif, else Execute statements if condition is true
switch, case, otherwise Execute one of several groups of statements
for for loop to repeat specified number of times
while while loop to repeat when condition is true
try, catch Execute statements and catch resulting errors
break Terminate execution of for or while loop
return Return control to invoking script or function
continue Pass control to next iteration of for or while loop
pause Stop MATLAB execution temporarily
parfor Parallel for-loop
end Terminate block of code or indicate last array index
Conditional Statements (if)
if expression
statements
elseif expression
statements
else
statements
end
If……end
% Generate a random number
a = randi(100, 1);
% If it is even, divide by 2
if rem(a, 2) == 0
disp('a is even')
b = a/2;
end
If…..elseif…..else…..end
a = randi(100, 1);
if a < 30
disp('small')
elseif a < 80
disp('medium')
else
disp('large')
end
Conditional Statements (switch)
[dayNum, dayString] = weekday(date, 'long', 'en_US');
switch dayString
case 'Monday'
NOTE: cannot test for inequality between switch and
disp('Start of the work week') case values
case 'Tuesday'
disp('Day 2')
case 'Wednesday'
Switch Statement
disp('Day 3')
case 'Thursday'
disp('Day 4')
The otherwise block executes the statements only when no
case 'Friday' case is true.
disp('Last day of the work week')
otherwise
disp('Weekend!')
end
Loop Control Statements (for loop)
x = ones(1,10);
for n = 2:6
end
Loop Control Statements (while loop)
n = 1;
nFactorial = 1;
n = n + 1;
nFactorial = nFactorial * n;
end
Example 1
nrows = 4; for c = 1:ncols
for r = 1:nrows
ncols = 6;
if r == c
A = ones(nrows,ncols); A(r,c) = 2;
elseif abs(r-c) == 1
A(r,c) = -1;
else
A(r,c) = 0;
end
end
end
Example 2
limit = 0.75; if any(A > limit)
else
end
Example 3
A = ones(2,3); if isequal(size(A),size(B))
else
C = [];
end
Example 4
reply = input('Would you like to see an
echo? (y/n): ','s');
if strcmp(reply,'y')
disp(reply)
end
Example 5
x = 10;
if x ~= 0
disp('Nonzero value')
end
Example 6
x = 10; disp('Value exceeds maximum value.')
minVal = 2; else
switch n
case -1
disp('negative one')
case 0
disp('zero')
case 1
disp('positive one')
otherwise
disp('other value')
end
Example 8
x = [12 64 24];
plottype = 'pie3';
switch plottype
case 'bar'
bar(x)
title('Bar Graph')
case {'pie','pie3'}
pie3(x)
title('Pie Chart')
otherwise
warning('Unexpected plot type. No plot
created.')
end
Example 9
result = 52;
switch(result)
case 52
disp('result is 52')
disp('result is 52 or 78')
end
Example 10
for v = [1 5 8 17]
disp(v)
end
Example 11
for I = eye(4,3)
disp(I)
end
Example 12
n = 10;
f = n;
while n > 1
n = n-1;
f = f*n;
end
count = 0; end
fclose(fid);
Example 14
limit = 0.8;
s = 0;
while 1
tmp = rand;
break
end
s = s + tmp;
end