Using for loops to generate an array?
33 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
采纳的回答
TastyPastry
2015-11-6
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 个评论
TastyPastry
2015-11-6
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.
更多回答(1 个)
Matt Tearle
2015-11-6
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.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!