For-loop matrix where the elements increase by 1

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!

답변 (1개)

Jan
Jan 2017년 10월 2일
편집: Jan 2017년 10월 2일

0 개 추천

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

Thanks for the prompt response!
I made a bit of process before seeing your answer. The matrix is meant to start at 1, increase by 1 across a row and stop at 30. now the only issue I am having is making the matrix appear once rather than 30 times.
This is the code I have:
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
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.
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

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2017년 10월 2일

댓글:

Jan
2017년 10월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by