我正在尝试编写一个函数,对每个元素的前 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 万个元素,所以我想知道是否有人可以给我任何关于如何加速该函数的建议。
最佳答案
使用 cumsum 应该更快:
function [res] = sumLastN(vec,ppts)
w=cumsum(vec)
res=[zeros(1,ppts-1),w(ppts+1:end)-w(1:end-ppts)]
end
关于matlab - 对于向量中的每个元素,将前 n 个元素相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24499423/