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