矢量划分的部分和

gob*_*bow 3 arrays matlab

如果有这样的矢量,

T = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16] 
Run Code Online (Sandbox Code Playgroud)

(矢量T的大小可以灵活)

我怎样才能获得一系列"分裂总和"

例如,

fn(T, 5) = [ (1+2+3+4+5) , (6+7+8+9+10), (11+12+13+14+15) , 16]
Run Code Online (Sandbox Code Playgroud)

the*_*alk 6

一个选项,不需要在原始数组上填充零,是使用accumarrayceil:

div = 5;
out = accumarray(ceil((1:numel(T))/div).',T(:))
Run Code Online (Sandbox Code Playgroud)

使用cumsumdiff替代的另一种选择:

div = 5;
T(ceil(numel(T)/div)*div) = 0;
cs = cumsum(T)
out = diff( [0 cs(div:div:end) ] )
Run Code Online (Sandbox Code Playgroud)

编辑:一旦填充完成,cumsum并且diff有点矫枉过正,应该按照Bentoy的回答继续进行.


Ben*_*y13 5

另一种方式,靠近thewaywewalk的第二个选项:

div = 5;
T(ceil(numel(T)/div)*div) = 0;
out = sum(reshape(T,div,[])).'; % transpose if you really want a column vector
Run Code Online (Sandbox Code Playgroud)

另外,一个单线解决方案(我更喜欢这个):

out = blockproc(T,[1 5], @(blk) sum(blk.data), 'PadPartialBlocks',true);
Run Code Online (Sandbox Code Playgroud)

不要忘记设置参数'PadPartialBlocks',这是避免显式填充的关键.