0
0
MATLABdata~5 mins

Nested loops in MATLAB

Choose your learning style9 modes available
Introduction

Nested loops let you repeat actions inside other repeated actions. This helps when you work with tables or grids.

When you want to check every cell in a table or matrix.
When you need to compare pairs of items in two lists.
When you want to create patterns with rows and columns.
When you process images pixel by pixel.
When you generate combinations of options.
Syntax
MATLAB
for outer = startValue : endValue
    for inner = startValue : endValue
        % Your code here
    end
end
The outer loop runs first, then the inner loop runs completely for each outer loop step.
Use different variable names for each loop to avoid confusion.
Examples
This prints pairs of numbers where i goes from 1 to 3 and j goes from 1 to 2.
MATLAB
for i = 1:3
    for j = 1:2
        disp([i, j])
    end
end
This prints row and column numbers in a grid style.
MATLAB
for row = 1:2
    for col = 1:3
        fprintf('Row %d, Col %d\n', row, col);
    end
end
Sample Program

This program uses nested loops to print all combinations of i and j values.

MATLAB
for i = 1:2
    for j = 1:3
        fprintf('i = %d, j = %d\n', i, j);
    end
end
OutputSuccess
Important Notes

Remember that the inner loop finishes all its steps before the outer loop moves to the next step.

Too many nested loops can make your program slow. Use them carefully.

Summary

Nested loops run one loop inside another to handle multi-level tasks.

They are useful for working with tables, grids, or combinations.

Always keep track of loop variables and their ranges.