How to form a matrix

1 次查看(过去 30 天)
Patrick
Patrick 2014-11-15
评论: Patrick 2014-11-15
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]?

采纳的回答

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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by