# Using for loops to generate an array?

조회 수: 3 (최근 30일)
Dominic Lira 2015년 11월 6일
답변: Matt Tearle 2015년 11월 6일
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 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없음 표시없음 숨기기
Dominic Lira 2015년 11월 6일
could you explain what's going on for the right side of the equation in line 4? (i:i:i*n)?
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.

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by