How to remove for-loop in computing a vector of sums?
Show older comments
How to compute rcross vector without the for-loop?
rcross = zeros( length(elementProduct) - prefixLen , 1 );
for ii = 1: length(elementProduct) - prefixLen
rcross(ii) = sum( elementProduct(ii : ii + prefixLen - 1) );
end
In one scenario prefixLen is 8. length(elementProduct) can vary from a few hundred to a few million.
6 Comments
KSSV
on 8 Dec 2020
It looks like a moving window.....have a look on movsum.
Paul Hoffrichter
on 8 Dec 2020
Edited: Paul Hoffrichter
on 8 Dec 2020
Thank you. Very close. prefixLen is 8. M is shifted to right by 4 points. Any way to adjust so that M is equal to rcross?
M = movsum( elementProduct, prefixLen );
I will check for odd prefixLen. May not be as good.
Image Analyst
on 8 Dec 2020
Edited: Image Analyst
on 8 Dec 2020
Another way is to use conv() and there you have options for how to handle end effects, like 'full', 'valid', or 'same'.
windowWidth = 9; % Usually an odd number but doesn't have to be.
kernel = ones(windowWidth);
outputSum = conv(elementProduct, kernel, 'same');
Paul Hoffrichter
on 8 Dec 2020
Edited: Paul Hoffrichter
on 8 Dec 2020
Had some issues with odd vs even prefixLen, but then found this one that worked. Thanks.
M = movsum( elementProduct, prefixLen, 'Endpoints','discard');
rcross and M were then off by extremely small amounts.
Paul Hoffrichter
on 8 Dec 2020
@KSSV,
Thank you for your comment. If you move it to an answer, I will accept it. Thanks again!
~Paul
Paul Hoffrichter
on 8 Dec 2020
I think your approach will also work. But I believe (without testing) that using conv would be slower than movsum.
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!