Control Structures in MATLAB Get Certified
Control structures are essential for guiding the flow of execution in MATLAB scripts and functions. They include conditional statements, loops, and other mechanisms that 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
Expected 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
Expected 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 Skipping even number: 2 Iteration: 3 Skipping even number: 4 Breaking the loop at 5
Useful MATLAB Keywords for Control Structures
if block.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.