对于向量中的每个元素,将前n个元素相加

时间:2014-06-30 21:45:05

标签: matlab optimization sum

我正在尝试编写一个函数,该函数对每个元素

的前n个元素求和
    v = [1 1 1 1 1 1];
    res = sumLastN(v,3);
    res = [0 0 3 3 3 3];

到现在为止,我已经写了以下函数

    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

大约有2000个载体,大约有100万个元素,所以我想知道是否有人能给我任何关于如何加速这个功能的建议。

2 个答案:

答案 0 :(得分:3)

使用cumsum应该快得多:

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

答案 1 :(得分:2)

你基本上想要一个移动平均滤波器,只是没有平均值。

使用数字filter

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

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

我不明白为什么前两个元素应为零,但为什么不呢:

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