# Using for loops to generate an array?

83 views (last 30 days)
Dominic Lira on 6 Nov 2015
Answered: Matt Tearle on 6 Nov 2015
I need to generate the array A = 1 2 3 4 5; 2 4 6 8 10; 3 6 9 12 15; 4 8 12 16 20; 5 10 15 20 25; using for loops. Don't have much experience with looping, and currently trying to understand it until it clicks. Help!

TastyPastry on 6 Nov 2015
m = 7; n = 6;
A = zeros(m,n);
for i=1:m
A(i,:) = i:i:i*n;
end
This should work for any size array with rows m and columns n.
##### 2 CommentsShowHide 1 older comment
TastyPastry on 6 Nov 2015
In this notation, a:b:c, a is the starting value for a vector. b is the increment between each value. c is the maximum value of the vector. c may or may not appear as the last value in the vector.
If you look at the pattern you're generating, the first number of each line is also the line number you're currently writing. Therefore, the first value is i, the line you're currently writing. Now the increment in each line is also the line number you're generating (line 1's increment is 1, line 2's increment is 2, and so on), so the step is also i. Finally, i*n is the final value of your line, equal to the first value multiplied by the number of values in each line, since your increment is equal to the first value in each line.

Matt Tearle on 6 Nov 2015
TastyPastry's answer is perfectly correct, but it's worth asking an important clarification: why do you want to do it with a for-loop? This can be done far more neatly in MATLAB without any loops.