How to save output from iteration?

1 次查看(过去 30 天)
Tara
Tara 2013-4-22
i have an array a=[1;2;2;3;4;4;4;4]; when i type
for i=1:3
[~,col]=find(a==1)
end
it only results col=1, i wanna save all of the col, it's like
col=1
1
1
what should i do? thank you
  2 个评论
Leah
Leah 2013-4-22
it's not clear what you are looping over since "i" does not appear inside the for loop. Also your desired output for col, doesn't really make sense since 1 only appears in the first entry of a. What do the three outputs for col mean?
Matt Kindig
Matt Kindig 2013-4-22
@Tara: For what it's worth, you can accomplish the same thing more efficiently by using ismember(), as:
[temp,locs]=ismember(a, 1:3);
% 'locs' will contain positions where 1,2,and 3 are found in 'a'

请先登录,再进行评论。

回答(1 个)

Walter Roberson
Walter Roberson 2013-4-22
for i = 1 : 3
[~, col{i}] = find(a==1);
end
Notice the switch to cell arrays. This is needed because any given value might occur 0, 1, or many times instead of exactly once.
Also notice you are doing exactly the same "find" each time. Perhaps you wanted to find over a(i,:) ?
  1 个评论
Tara
Tara 2013-4-24
编辑:Tara 2013-4-24
@walter,how about my code bellow
for i=1:length(maxprob)
pred=find(numb==3); % this results index of number
if length(pred)>1
pred=0;
else
pred;
end
end
it only results the final answer, not all the result of iteration. can you help me? thank you

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by