Save FOR loop data into a vector

조회 수: 66 (최근 30일)
Agent Cooper
Agent Cooper 2014년 2월 13일
댓글: Agent Cooper 2014년 2월 13일
Dear all,
I am trying to save the data that I get from a FOR loop into a vector. Here is my example:
X = [ -5 1 -2 9 100 -3 ]
for i = X(1:1:end)
if find(0<i & i<10) == 1
Y = i
else Y = NaN
end
end
The above code returns the values after each iteration, separately. I would like them placed into a vector. Could anyone give me a hint on that?

채택된 답변

Iain
Iain 2014년 2월 13일
You need your for loop to index into X, rather than use X as the index.
for j = 1:numel(X)
i = X(j);
your code as normal...
output(j) = Y;
end
  댓글 수: 1
Agent Cooper
Agent Cooper 2014년 2월 13일
Thank you very much, Iain. It works just fine now.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jos (10584)
Jos (10584) 2014년 2월 13일
Note that you can loop over elements
X = [1 3 5 2 3 4 1]
Y = zeros(size(X)) ; % pre-allocation makes loops faster
k = 0 ;
for xval = X
k = k + 1 ;
disp(xval)
if xval > 2
Y(k) = 1 ;
end
end
But … matlab can handle vectors/arrays at once, making this much easier!
Y = double(X>2) % X>2 would return a logical array.
  댓글 수: 1
Agent Cooper
Agent Cooper 2014년 2월 13일
Thank you very much for your answer, Jos.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by