Academic Block

Logo of Academicblock.net

Control Structures in MATLAB

Control structures are essential for guiding the flow of execution in MATLAB scripts and functions. They include conditional statements, loops, and other mechanisms to enable complex computations and decision-making processes.

Conditional Statements

MATLAB supports conditional execution using if, else, elseif, and switch statements.

If-Else Statement

% Example of if-else
x = 10;
if x > 0
disp('x is positive');
elseif x == 0
disp('x is zero');
else
disp('x is negative');
end
Output: x is positive

Switch Statement

% Example of switch
choice = 2;
switch choice
case 1
disp('Choice is 1');
case 2
disp('Choice is 2');
otherwise
disp('Invalid choice');
end
Output: Choice is 2

Loops

Loops are used for repetitive execution of code blocks. MATLAB provides for and while loops.

For Loop

% Example of for loop
for i = 1:5
disp(['Iteration: ', num2str(i)]);
end
Output: 

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

While Loop

% Example of while loop
n = 0;
while n < 5
n = n + 1;
disp(['Value of n: ', num2str(n)]);
end
Output: 

Value of n: 1
Value of n: 2
Value of n: 3
Value of n: 4
Value of n: 5

Break and Continue

You can use break to exit a loop prematurely and continue to skip to the next iteration.

% Example of break and continue
for i = 1:10
if i == 5
disp('Breaking the loop at 5');
break;
elseif mod(i, 2) == 0
disp(['Skipping even number: ', num2str(i)]);
continue;
end
disp(['Iteration: ', num2str(i)]);
end
Output: 

Iteration: 1
Iteration: 3
Iteration: 5
Breaking the loop at 5

Useful MATLAB Functions for Control Structures

Function
Explanation
if
Executes code based on a condition.
elseif
Specifies additional conditions in an if block.
else
Specifies the code to execute if no conditions are met.
switch
Switches execution based on a value.
for
Loops a fixed number of times.
while
Loops while a condition is true.
break
Exits the current loop.
continue
Skips to the next iteration of the loop.

Practice Questions

Test Yourself

1. Write a program to print the first 10 Fibonacci numbers using a while loop.

2. Use a for loop to calculate the factorial of a number.

3. Create a menu-driven program using a switch statement.