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

1 visualizzazione (ultimi 30 giorni)
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 Commenti
Matt J
Matt J il 3 Ago 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".

Accedi per commentare.

Risposta accettata

Matt J
Matt J il 3 Ago 2020
Modificato: Matt J il 3 Ago 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 Commenti
Matt J
Matt J il 3 Ago 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.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by