Matlab 12
Matlab 12
Objective
To explore and implement different types of loops in MATLAB for iterative tasks and automation.
Theory
Loops are fundamental constructs in programming used for executing a block of code multiple times.
MATLAB supports two primary types of loops:
1. For Loop
Executes a block of code for a fixed number of iterations.
Syntax:
% Code to execute
end
2. While Loop
Executes a block of code as long as a condition is true.
Syntax:
while condition
% Code to execute
end
Key Points:
Proper initialization and termination conditions are essential to avoid infinite loops.
Materials Required
MATLAB Software
Procedure
1. For Loop: Create a for loop to calculate and display the squares of numbers from 1 to 10.
for i = 1:10
square = i^2;
end
2. While Loop: Create a while loop to calculate the factorial of a given number.
n = 5; % Example number
factorial = 1;
i = 1;
while i <= n
factorial = factorial * i;
i = i + 1;
end
3. Nested Loops: Use nested loops to generate a multiplication table for numbers 1 to 5.
for i = 1:5
for j = 1:5
product = i * j;
end
fprintf('\n');
end
for i = 1:10
if i == 6
break;
end
disp(i);
end
o Continue: Skip the rest of the current iteration and continue with the next iteration.
for i = 1:10
if mod(i, 2) == 0
continue;
end
fprintf('%d is odd\n', i);
end
Observations
Conclusion
Loops in MATLAB are powerful tools for automating repetitive tasks. Understanding their use and
control mechanisms, such as break and continue, enhances programming efficiency.
Code
for i = 1:10
square = i^2;
end
n = 5; % Example number
factorial = 1;
i = 1;
while i <= n
factorial = factorial * i;
i = i + 1;
end
for j = 1:5
product = i * j;
end
fprintf('\n');
end
for i = 1:10
if i == 6
break;
end
disp(i);
end
for i = 1:10
if mod(i, 2) == 0
continue;
end
end