for loops and nested for loops in matlab

A for loop can be used in MATLAB to iterate over a set of values, such as a vector or array. The basic syntax of a for loop in MATLAB is as follows:

main.m
for index = values
   statements
end
37 chars
4 lines

Where index is a loop variable that takes on each value in the values array, and statements is the code that should be executed during each iteration of the loop.

For example, the following code uses a for loop to iterate over a vector x, squaring each element and storing the result in a new vector y:

main.m
x = 1:5;
y = zeros(1,5);
for i = 1:length(x)
   y(i) = x(i)^2;
end
disp(y)
75 chars
7 lines

Output:

main.m
[1  4  9 16 25]
16 chars
2 lines

A nested for loop has one or more for loops nested inside another for loop. This is often used to iterate over a 2D matrix or array. The basic syntax for a nested for loop is as follows:

main.m
for index1 = values1
   for index2 = values2
      statements
   end
end
73 chars
6 lines

Where index1 and index2 are loop variables that take on each value in the values1 and values2 arrays, respectively, and statements is the code that should be executed during each iteration of the nested loops.

For example, the following code uses a nested for loop to iterate over a 2D matrix A, calculating the sum of each row and storing the result in a new vector sums:

main.m
A = [1 2 3; 4 5 6; 7 8 9];
[m,n] = size(A);
sums = zeros(1,m);
for i = 1:m
   row_sum = 0;
   for j = 1:n
      row_sum = row_sum + A(i,j);
   end
   sums(i) = row_sum;
end
disp(sums)
184 chars
12 lines

Output:

main.m
[ 6 15 24]
11 chars
2 lines

gistlibby LogSnag