Improve speed of for loop

1 visualizzazione (ultimi 30 giorni)
Anna van der Stap
Anna van der Stap il 22 Mar 2021
I have a for loop as follows:
for z = 1:r %run through data from start to end
x = row14 >= (z-1)*tp & row14 <= z*tp; % run through in steps the size of your time bins
s(z) = nnz(x);
end
However, I'm working with really large matrices, r = 56043, and row14 is 1x19609285 double. As a result this particular for loop takes absolutely ages. Is there any way that I can improve the performance to speed up the process a bit?

Risposta accettata

Walter Roberson
Walter Roberson il 22 Mar 2021
idx = floor(row14 ./ tp) + 1;
counts = accumarray(idx(:), 1);
counts(end+1:r) = 0;
Or
counts = histcounts(row14, (0:r)*tp);
or
counts = histcounts(row14, 'binwidth', tp);
Caution: the binwidth will not be respected if the data implies more than 2^16 bins.

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