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

1 visualización (últimos 30 días)
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 comentarios
Matt J
Matt J el 3 de Ag. de 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".
Anita Nabatanzi
Anita Nabatanzi el 3 de Ag. de 2020
or sorry i did mean less than or equal to

Iniciar sesión para comentar.

Respuesta aceptada

Matt J
Matt J el 3 de Ag. de 2020
Editada: Matt J el 3 de Ag. de 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 comentarios
Matt J
Matt J el 3 de Ag. de 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.
Anita Nabatanzi
Anita Nabatanzi el 3 de Ag. de 2020
Thats a significant time lag! Thanks Matt

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by