For-loop matrix where the elements increase by 1
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Jan
am 2 Okt. 2017
Bearbeitet: Jan
am 2 Okt. 2017
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 Kommentare
Walter Roberson
am 2 Okt. 2017
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
am 3 Okt. 2017
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
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!