return a single vector after a for loop and not individual results

1 view (last 30 days)
I am working on a large set of data (600x300) but will illustrate with the reduced set below; For each row, I would like the code to determine the first number less than 5 and return the location of that number (which would be the column number), if there is no number less than 5 like in row 2, it returns nothing. This seems to work fine but unfortunately only returns individual results yet i would want the code to return a vector (in this case 3x1) with all results in one variable. I have tried several options like creating a zero matrix and assigning new results to it among others but have not been successful, shall be grateful for your help.
Divergence=[9,8,5,6,7;10,11,13,15,14;1,2,18,19,10]
for row=1:3
rowdata=Divergence(row,:)
place=find(rowdata<=5,1)
end
  2 Comments
Matt J
Matt J on 3 Aug 2020
I would like the code to determine the first number less than 5
Here you say "less than", but your code says "less than or equal to".

Sign in to comment.

Accepted Answer

Matt J
Matt J on 3 Aug 2020
Edited: Matt J on 3 Aug 2020
For a fully vectorized solution:
[maxval,place]=max(Divergence<=5,[],2);
place(maxval==0)=nan;
Or, to do the same with a loop,
[m,n]=size(Divergence);
place=nan(m,1); %PREALLOCATE
for row=1:m
rowdata=Divergence(row,:);
tmp=find(rowdata<=5,1);
if ~isempty(tmp)
place(row)=tmp;
end
end
  5 Comments
Matt J
Matt J on 3 Aug 2020
The vectorized solution will be faster for large data sets. Compare:
Divergence=randi(18,5000,5000);
tic;
[m,n]=size(Divergence);
place=nan(m,1); %PREALLOCATE
for row=1:m
rowdata=Divergence(row,:);
tmp=find(rowdata<=5,1);
if ~isempty(tmp)
place(row)=tmp;
end
end
toc %Elapsed time is 0.275612 seconds.
tic
[maxval,place]=max(Divergence<=5,[],2);
place(maxval==0)=nan;
toc %Elapsed time is 0.025761 seconds.

Sign in to comment.

More Answers (0)

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!