Control Flow
## Learning Objectives
- Use conditional statements (if-else, switch)
- Implement loops (for, while)
- Control loop execution (break, continue)
- Handle errors appropriately
## Conditional Statements
### if Statement
```matlab
x = 10;
if x > 0
disp('x is positive');
end
```
### if-else Statement
```matlab
x = -5;
if x >= 0
disp('x is non-negative');
else
disp('x is negative');
end
```
### if-elseif-else Statement
```matlab
score = 85;
if score >= 90
grade = 'A';
elseif score >= 80
grade = 'B';
elseif score >= 70
grade = 'C';
elseif score >= 60
grade = 'D';
else
grade = 'F';
end
disp(grade); % 'B'
```
### Nested if Statements
```matlab
x = 10;
y = 20;
if x > 0
if y > 0
disp('Both x and y are positive');
else
disp('x positive, y non-positive');
end
else
disp('x is not positive');
end
```
## switch Statement
### Basic switch
```matlab
day = 'Monday';
switch day
case 'Monday'
disp('Start of work week');
case 'Friday'
disp('End of work week');
case {'Saturday', 'Sunday'}
disp('Weekend!');
otherwise
disp('Regular day');
end
```
### Multiple Values per Case
```matlab
month = 2;
switch month
case {1, 3, 5, 7, 8, 10, 12}
days = 31;
case {4, 6, 9, 11}
days = 30;
case 2
days = 28;
end
```
### switch vs if-else
```matlab
% switch is often cleaner for discrete values
% if-else is better for ranges or complex conditions
% Example with ranges (if-else is better)
value = 75;
if value >= 90
result = 'A';
elseif value >= 80
result = 'B';
else
result = 'C';
end
```
## for Loops
### Basic for Loop
```matlab
% Loop through a range
for i = 1:5
fprintf('i = %d\n', i);
end
```
### Loop Through Array
```matlab
arr = [10, 20, 30, 40, 50];
sum = 0;
for val = arr
sum = sum + val;
end
disp(sum); % 150
```
### Nested for Loops
```matlab
% Print multiplication table
for i = 1:5
row = '';
for j = 1:5
row = [row, sprintf('%4d', i*j)];
end
disp(row);
end
```
### Loop with Step
```matlab
% Even numbers from 2 to 10
for i = 2:2:10
disp(i); % 2, 4, 6, 8, 10
end
% Backwards
for i = 10:-1:1
disp(i); % 10, 9, 8, ..., 1
end
```
### Loop Index Variations
```matlab
A = [1, 2, 3; 4, 5, 6];
% Loop through row and column indices
[m, n] = size(A);
for i = 1:m
for j = 1:n
fprintf('A(%d,%d) = %d\n', i, j, A(i,j));
end
end
```
## while Loops
### Basic while Loop
```matlab
count = 0;
while count < 5
disp(count);
count = count + 1;
end
```
### while with Condition
```matlab
% Find first power of 2 greater than 1000
value = 1;
while value <= 1000
value = value * 2;
end
disp(value); % 1024
```
### Infinite Loop Prevention
```matlab
% Always ensure loop condition will eventually be false
maxIterations = 100;
count = 0;
x = 1;
while abs(x) > 1e-10 && count < maxIterations
x = x / 2;
count = count + 1;
end
if count == maxIterations
disp('Max iterations reached');
end
```
## break and continue
### break Statement
```matlab
% Find first even number in array
arr = [1, 3, 5, 7, 8, 9, 10];
for val = arr
if mod(val, 2) == 0
disp(['First even: ', num2str(val)]);
break;
end
end
```
### continue Statement
```matlab
% Print odd numbers only
for i = 1:10
if mod(i, 2) == 0
continue; % Skip even numbers
end
disp(i); % 1, 3, 5, 7, 9
end
```
### break vs continue
```matlab
% break - exits the loop entirely
% continue - skips to next iteration
```
## Loop Control Examples
### Sum Until Condition
```matlab
% Sum array elements until sum exceeds 100
arr = [10, 20, 30, 40, 50, 60];
sum = 0;
for i = 1:length(arr)
sum = sum + arr(i);
if sum > 100
break;
end
end
fprintf('Sum: %d, Elements used: %d\n', sum, i);
```
### Skip Invalid Values
```matlab
% Process only positive values
data = [-5, 10, -3, 20, -1, 30];
validSum = 0;
for val = data
if val <= 0
continue;
end
validSum = validSum + val;
end
disp(validSum); % 60
```
## Vectorization (Alternative to Loops)
### Replace Loops with Vector Operations
```matlab
% Slow: Loop approach
n = 1000;
result = zeros(1, n);
for i = 1:n
result(i) = i^2;
end
% Fast: Vectorized approach
result = (1:n).^2;
```
### Logical Indexing
```matlab
% Find elements greater than 5
arr = [1, 6, 3, 8, 2, 9];
% Loop approach
large = [];
for val = arr
if val > 5
large = [large, val];
end
end
% Vectorized approach
large = arr(arr > 5);
```
## Error Handling
### try-catch
```matlab
try
result = 10 / 0;
disp('Division succeeded');
catch ME
disp('Error occurred:');
disp(ME.message);
end
```
### Multiple catch Blocks
```matlab
try
x = notAFunction();
catch ME
if strcmp(ME.identifier, 'MATLAB:UndefinedFunction')
disp('Function not found');
else
disp(['Error: ', ME.message]);
end
end
```
## Summary
- Use `if-elseif-else` for conditional logic
- Use `switch` for discrete value matching
- Use `for` loops when iteration count is known
- Use `while` loops when condition-based iteration needed
- Use `break` to exit loops early
- Use `continue` to skip iterations
- Prefer vectorization over loops for performance
- Use `try-catch` for error handling
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →