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!

回答(1 个)

Jan
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
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
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 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