Loops and Conditional
Statements
Control flow and branching using keywords,
such as if, for, and while
1/30/2025 Loops and Conditional Statements 1
Loops and Conditional Statements
Conditional statements with the
proper comparison and boolean
operators allow the creation of
alternate execution paths in the code.
Loops allow repeated execution of
the same set of statements on all the
objects within a sequence.
Jump statements allow you to exit
a loop, start the next iteration of a loop,
or explicitly transfer program control
to a specified location in your program.
1/30/2025 Loops and Conditional Statements 2
FOR Loop for loop to repeat specified number of times
Execute Statements for
Decrement Values Specified Values
for index = values for v = 1.0:-0.2:0.0
statements disp(v) for v = [1 5 8 17]
end end disp(v)
end
Repeat Statements for Selectively Display Values in
Each Matrix Column Assign Matrix Values
Loop : continue
s = 10;
for I = eye(4,3) H = zeros(s); for n = 1:50
disp('Current unit vector:') if mod(n,7)
disp(I) for c = 1:s continue
end for r = 1:s end
H(r,c) = 1/(r+c-1); disp(['Divisible by 7: ' num2str(n)])
end end
end
1/30/2025 Loops and Conditional Statements 3
WHILE Loop while loop to repeat when condition is true
while expression
statements
end
Exit Loop Before Expression Is False
Repeat Statements Until limit = 0.8;
Expression Is False s = 0;
n = 10; while 1
f = n; tmp = rand;
while n > 1 if tmp > limit
n = n-1; break
f = f*n; end
end s = s + tmp;
disp(['n! = ' num2str(f)]) end
1/30/2025 Loops and Conditional Statements 4
Conditional statements
Conditional statements enable you to select at run time which block of code to execute.
Some examples : [dayNum, dayString] = weekday(date, 'long', 'en_US');
% Generate a random number a = rand(100, 1); switch dayString
a = rand(100, 1); case 'Monday'
if a < 30 disp('Start of the work week')
% If it is even, divide by 2 disp('small') case 'Tuesday'
if rem(a, 2) == 0 elseif a < 80 disp('Day 2')
disp('a is even') disp('medium') case 'Wednesday'
b = a/2; else disp('Day 3')
end disp('large') case 'Thursday'
end disp('Day 4')
case 'Friday'
disp('Last day of the work week')
otherwise
disp('Weekend!')
end
1/30/2025 Loops and Conditional Statements 5
return
return the control to the invoking program before it reaches the end of the script or function.
Return Control to Keyboard Return Control to Invoking Function
function idx = findSqrRootIndex(target,arrayToSearch) function returnControlExample(target)
idx = NaN; arrayToSearch = [3 7 28 14 42 9 0];
if target < 0 idx = findSqrRootIndex(target,arrayToSearch);
return
end if isnan(idx)
for idx = 1:length(arrayToSearch) disp('Square root not found.')
if arrayToSearch(idx) == sqrt(target) else
return disp(['Square root found at index ' num2str(idx)])
end end
end end
>>A = [3 7 28 14 42 9 0];
>>b = 81; >> returnControlExample(49)
>> findSqrRootIndex(b,A) >> Square root found at index 2
1/30/2025 Loops and Conditional Statements 6