nested for loop in matlab

A nested loop is a loop inside another loop. In Matlab, the syntax for a nested loop is as follows:

main.m
for i=1:N
   for j=1:M
      % code to be executed
   end
end
62 chars
6 lines

Here, the outer loop iterates from 1 to N, while the inner loop iterates from 1 to M for each value of i. The code inside the inner loop is executed M times for each iteration of the outer loop.

For example, consider the following code, which initializes a 3x3 matrix with random numbers:

main.m
A=zeros(3,3);
for i=1:3
    for j=1:3
        A(i,j)=rand;
    end
end
disp(A)
79 chars
8 lines

In this code, the outer loop iterates over the rows of the matrix, while the inner loop iterates over the columns of the matrix. The rand function generates a random number between 0 and 1, which is assigned to the current element of the matrix.

This will output a 3x3 matrix with random values, like this:

main.m
0.2511    0.6160    0.7340
0.6160    0.4733    0.4387
0.7340    0.4387    0.3816
81 chars
4 lines

gistlibby LogSnag