Improve speed of for loop

1 次查看(过去 30 天)
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?

采纳的回答

Walter Roberson
Walter Roberson 2021-3-22
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by