For-loop matrix where the elements increase by 1
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (1)
Jan
el 2 de Oct. de 2017
Editada: Jan
el 2 de Oct. de 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 comentarios
Walter Roberson
el 2 de Oct. de 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
el 3 de Oct. de 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
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!