Clear Filters
Clear Filters

How to save output from iteration?

1 view (last 30 days)
Tara
Tara on 22 Apr 2013
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 Comments
Leah
Leah on 22 Apr 2013
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 on 22 Apr 2013
@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'

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 22 Apr 2013
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 Comment
Tara
Tara on 24 Apr 2013
Edited: Tara on 24 Apr 2013
@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

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!