Loops can be nested, to preform iterated task within another iterated task. Consider the following loops:
ch = 'abc';
m = 3;
for c = ch
for k = 1:m
disp([c num2str(k)]) % NUM2STR converts the number stored in k to a charachter,
% so it can be concataneted with the letter in c
end
end
we use 2 iterators to display all combinations of elements from abc
and 1:m
, which yields:
a1
a2
a3
b1
b2
b3
c1
c2
c3
We can also use nested loops to combine between tasks to be done each time, and tasks to be done once in a several iterations:
N = 10;
n = 3;
a1 = 0; % the first element in Fibonacci series
a2 = 1; % the secound element in Fibonacci series
for j = 1:N
for k = 1:n
an = a1 + a2; % compute the next element in Fibonacci series
a1 = a2; % save the previous element for the next iteration
a2 = an; % save ht new element for the next iteration
end
disp(an) % display every n'th element
end
Here we want to compute all the Fibonacci series, but to display only the n
th element each time, so we get
3
13
55
233
987
4181
17711
75025
317811
1346269
Another thing we can do is to use the first (outer) iterator within the inner loop. Here is another example:
N = 12;
gap = [1 2 3 4 6];
for j = gap
for k = 1:j:N
fprintf('%d ',k) % FPRINTF prints the number k proceeding to the next the line
end
fprintf('\n') % go to the next line
end
This time we use the nested loop to format the output, and brake the line only when a new gap (j
) between the elements was introduced. We loop through the gap width in the outer loop and use it within the inner loop to iterate through the vector:
1 2 3 4 5 6 7 8 9 10 11 12
1 3 5 7 9 11
1 4 7 10
1 5 9
1 7