Improve speed of for loop

2 views (last 30 days)
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?

Accepted Answer

Walter Roberson
Walter Roberson on 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.

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!