How to remove for-loop in computing a vector of sums?

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

It looks like a moving window.....have a look on movsum.
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.
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');
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.
@KSSV,
Thank you for your comment. If you move it to an answer, I will accept it. Thanks again!
~Paul
I think your approach will also work. But I believe (without testing) that using conv would be slower than movsum.

Sign in to comment.

Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Release

R2020a

Asked:

on 8 Dec 2020

Community Treasure Hunt

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

Start Hunting!