Partial sum of vector divisions

If such a vector exists,

T = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16] 

      

(vector size T can be flexible)

How can I get an array of 'divisions sums ?

For example,

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

      

+3


source to share


3 answers


One parameter that does not require padding with zeros in the original array is using and : accumarray

ceil

div = 5;
out = accumarray(ceil((1:numel(T))/div).',T(:))

      

Another option using and : cumsum

diff



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

      

Edit: after filling is complete, cumsum

and is a diff

little overdone and needs to continue as in Bentoy's answer .

+6


source


Another way, close to the second variant of thewaywewalk :

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

      

Also, one one-line solution (I prefer this one):



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

      

Don't forget to set the "PadPartialBlocks" parameter, this is the key to preventing explicit padding.

+5


source


There is a built-in function vec2mat

in Communications System Toolbox

to convert a vector to a 2D matrix, which is turned off after every N elements and placed on separate rows, filling the remaining trailing spaces with zeros to maintain the 2D size. Thus, after use vec2mat

, the sum of all the rows will be enough to give you the desired result. Here's the implementation -

sum(vec2mat(T,5),2)

      

Example run -

>> T = 1:16;
>> vec2mat(T,5)
ans =
     1     2     3     4     5
     6     7     8     9    10
    11    12    13    14    15
    16     0     0     0     0
>> sum(vec2mat(T,5),2)
ans =
    15
    40
    65
    16

      

+4


source







All Articles