matlab - Sum of groups of four in a matrix -


i have following matrix: first column values of 1 5, second column 1 20, , third column random values.

1   1   2545 1   2   0 1   3   0 1   4   0 2   5   0 2   6   0 2   7   231 2   8   54587 3   9   41 3   10  1111 3   11  0 3   12  1213 4   13  0 4   14  0 4   15  0 4   16  0 5   17  898 5   18  6887 5   19  522 5   20  23     

what trying sum in groups of 4 when values different of zero. example, in matrix output want is:

1   nan 2   nan 3   nan 4   nan 5   8330 

assuming first column delineates values in third column belong group, easiest change values 0 nan, use accumarray sum of values belong each group. crucial because sum on matrix / array , any value nan, result nan. nice because if sum on each group, nan result if @ least 1 of values in group equal 0 before change.

i'm going assume matrix stored in x so:

x = [1   1   2545 1   2   0 1   3   0 1   4   0 2   5   0 2   6   0 2   7   231 2   8   54587 3   9   41 3   10  1111 3   11  0 3   12  1213 4   13  0 4   14  0 4   15  0 4   16  0 5   17  898 5   18  6887 5   19  522 5   20  23 ]; 

make copy of third column, , let's magic:

col = x(:,3); col(col == 0) = nan; out = accumarray(x(:,1), col); 

we get:

out =           nan          nan          nan          nan         8330 

the nice thing approach group id each value in matrix doesn't have in order have placed in post.


if matrix guaranteed have order each group consists of consecutive 4-tuples of elements, can same thing nan assignment, can avoid using accumarray , reshape third column matrix of 4 rows sum on each row individually:

col = x(:,3); col(col == 0) = nan; out = sum(reshape(col, 4, []), 1); 

Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -