Jelision
Jelision

Reputation: 23

For each element in vector, sum previous n elements

I am trying to write a function that sums the previous n elements for each the element

    v = [1 1 1 1 1 1];
    res = sumLastN(v,3);
    res = [0 0 3 3 3 3];

Until now, I have written the following function

    function [res] = sumLastN(vec,ppts)

        if iscolumn(vec)~=1
            error('First argument must be a column vector')
        end

        sz_x = size(vec,1);
        res = zeros(sz_x,1);
        if sz_x > ppts
            for jj = 1:ppts
                res(ppts:end,1) = res(ppts:end,1) + ...
                    vec(jj:end-ppts+jj,1);
            end
    %         for jj = ppts:sz_x
    %             res(jj,1) = sum(vec(jj-ppts+1:jj,1));
    %         end
        end

    end

There are around 2000 vectors of about 1 million elements, so I was wondering if anyone could give me any advice of how I could speed up the function.

Upvotes: 2

Views: 300

Answers (2)

Robert Seifert
Robert Seifert

Reputation: 25232

You basically want a moving average filter, just without the averaging.

Use a digital filter:

n = 3;
v = [1 1 1 1 1 1];

res = filter(ones(1,n),1,v)
res =
         1     2     3     3     3     3

I don't get why the first two elements should be zero, but why not:

res(1:n-1) = 0
res =
         0     0     3     3     3     3

Upvotes: 2

Daniel
Daniel

Reputation: 36710

Using cumsum should be much faster:

function [res] = sumLastN(vec,ppts)
w=cumsum(vec)
res=[zeros(1,ppts-1),w(ppts+1:end)-w(1:end-ppts)]
end

Upvotes: 3

Related Questions