For-loop matrix where the elements increase by 1
조회 수: 8 (최근 30일)
이전 댓글 표시
Hey all, I need to make a 6x5 matrix from 1:30. so far I have this:
c = 1;
d = 1;
count = 1;
for row = 1:6;
for col = 1:5;
A(row,col) = c,d;
c = c + 1;
d = d + 1;
count = count + 1;
if count>30;
break
end
end
end
This is successful at producing the matrix, however the matrix shows up 30 times when I run the script. How do I make it only show up once? Thanks!
댓글 수: 0
답변 (1개)
Jan
2017년 10월 2일
편집: Jan
2017년 10월 2일
The elements increase by 1. This leaves some degrees of freedom: Should the increasing be row-wise or column-wise? What is the start value?
I all cases this will help:
c = 1; % Start value
for row = 1:6
for col = 1:5
c = c + 1
end
end
I leave it up to you to fill this into your array.
Note that this can be done more efficiently in Matlab without loops. You need only 1:30 and the reshape function.
댓글 수: 3
Walter Roberson
2017년 10월 2일
The line
A(row,col) = c,d;
is equivalent to
A(row,col) = c
d;
which assigns c into that position of array A, displays the result of the assignment, and then calculates d and throws away the result of the calculation of d because of the semi-colon after it.
The line does not store the pair of values [c, d] into the location A(row,col). Numeric arrays like your A cannot store multiple values in the same location. You would need
A(row,col) = {[c,d]};
or
A{row,col} = [c,d];
to store the pair of values in the single location in A, which would have to be a cell array.
Jan
2017년 10월 3일
I do not understand, why you use 3 counters: counter, c, d. As far as I understand one counter is sufficient already. The loops stops after 5*6=30 iterations at all, so there is no need for a break:
c = 1;
for row = 1:6
for col = 1:5
A(row,col) = c;
c = c + 1;
end
end
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!