How to form a matrix

1 visualización (últimos 30 días)
Patrick
Patrick el 15 de Nov. de 2014
Comentada: Patrick el 15 de Nov. de 2014
I am using 'for loop' with variable 'i' to run something. i.e. for i = 1:100, .... Say, I want to record the value of i when it equals to 4, 6, 9, 12. How can I group them into a matrix so that the output can be like, M = [4 6 9 12]?

Respuesta aceptada

David Young
David Young el 15 de Nov. de 2014
The question doesn't entirely make sense. You say you want to record the value of i when i equals 4, 6, 9, 12. Taking the question literally, you could do this
k = 0; % initialise index into M
for i = 1:100
if ismember(i, [4 6 9 12]) % test whether i is at an interesting place
k = k + 1; % increment index
M(k) = i; % store the value of i in M
end
end
but if that was really what you wanted you'd just do
M = [4 6 9 12];
in the first place.
Perhaps you could clarify what exactly you need to do.
(By the way, some people regard i as a bad choice of name for a variable, because it is also a name for the square root of -1 in MATLAB.)
  1 comentario
Patrick
Patrick el 15 de Nov. de 2014
Sorry for not being clear but you got what I mean, thanks for your help, David.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by