How to form a matrix
1 次查看(过去 30 天)
显示 更早的评论
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]?
0 个评论
采纳的回答
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.)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!