Filter löschen
Filter löschen

How to form a matrix

1 Ansicht (letzte 30 Tage)
Patrick
Patrick am 15 Nov. 2014
Kommentiert: Patrick am 15 Nov. 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]?

Akzeptierte Antwort

David Young
David Young am 15 Nov. 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 Kommentar
Patrick
Patrick am 15 Nov. 2014
Sorry for not being clear but you got what I mean, thanks for your help, David.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing 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!

Translated by