Azzera filtri
Azzera filtri

Vectorizing a loop calculation

1 visualizzazione (ultimi 30 giorni)
Azura Hashim
Azura Hashim il 24 Feb 2018
Commentato: Meade il 26 Feb 2018
Hi,
Is it possible to convert the loop below into a vector calculation? Thank you.
dataset=table();
dataset.value=rand(30,1);
dataset.time=sort(rand(30,1));
timefilter=dataset.time-0.2;
result1=repmat(NaN,height(dataset),1);
result2=repmat(NaN,height(dataset),1);
result3=repmat(NaN,height(dataset),1);
%Loop:
for row=5:height(dataset)
startrow=min(find(dataset.time >=timefilter(row)));
result1(row,1)=nansum(dataset.value(startrow:row));
result2(row,1)=length(dataset.value(startrow:row));
result3(row,1)=nanstd(dataset.value(startrow:row)) ;
end
  3 Commenti
Azura Hashim
Azura Hashim il 26 Feb 2018
Thanks. Yes nansum and nanstd is not required here. I took it from the code that handles the full size data which has NaNs.
Meade
Meade il 26 Feb 2018
The sum, length, and std calculations are so trivially fast that it might be fastest to calculate them for the entire array, then just sort. If this doesn't seem unreasonable for your use, I would use bsxfun or arrayfun on your data, then sort. That would be fastest I think.
That would get rid of the loop entirely.

Accedi per commentare.

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