LAB 2 - Manual
LAB 2 - Manual
‘for’ statement:
for statements loop a specific number of times, and keep track of each iteration with an
incrementing index variable
Syntax of a for statement is
for i = 1:N
commands
end
Example:
s = 10;
H = zeros(s);
for c = 1:s
for r = 1:s
H(r,c) = 1/(r+c-1);
end
end
Try to run the code and write down your observations:
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
‘while’ statement:
while statements loop as long as a condition remains true.
Syntax of a while statement is
while (condition)
commands...
end
Example:
n = 10;
f = n;
while n > 1
n = n-1;
f = f*n;
end
Try to run the code and write down your observations:
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
Each loop requires the end keyword.
Conditional Statements:
Conditional statements enable you to select at run time which block of code to execute. There are
two types of conditional statements:
if-else statement:
Syntax of if-else statement is
if (expression)
commands...
end
Example:
a = randi(100, 1);
if a < 30
disp('small')
elseif a < 80
disp('medium')
else
disp('large')
end
switch dayString
case 'Monday'
case 'Tuesday'
disp('Day 2')
case 'Wednesday'
disp('Day 3')
case 'Thursday'
disp('Day 4')
case 'Friday'
otherwise
disp('Weekend!')
end