Nested Loops in MATLAB
Introduction to Nested Loops:
Nested loops are loops placed inside other loops.
Syntax:
for i = 1:n
for j = 1:m
% Statements
end
end
Example:
for i = 1:3
for j = 1:3
fprintf('i=%d, j=%d\n', i, j);
end
end
Explanation:
- Outer loop runs first, and inner loop runs completely for each iteration of the outer loop.
Applications of Nested Loops:
Example 1: Generating a Matrix
for x = 1:3
for y = 1:3
matrix(x, y) = x * y;
end
end
disp(matrix);
Example 2: Grid Plotting
for x = 1:5
for y = 1:5
z(x, y) = x^2 + y^2;
end
end
surf(z);