Tuesday, May 05, 2009

Matlab: Vector manipulation.

OP here.


Q:

Suppose I have

p = [ 0.81 0.90 0.12 0.91 0.63 0.09 0.27 0.54 0.95 0.96 0.15 0.97 0.95 0.48 0.80 0.14 0.42 0.21 0.54 0.14];

v = [ 1 0 0 1 0 1 0 1 1 1 1 1 0 0 0 0 1 1 0 1];



Where the 1 defines the boundary of blocks. So the first block is 1 0 0, second 1 0, third 1 0, fourth 1, fifth 1, ... and so on.

I want to sum values in p according to blocks defined by v. The output in this case should look like:

r = [1.83 1.54 0.36 0.54 0.95 0.96 0.15 3.34 0.42 0.75 0.14];



A:

r = accumarray(cumsum(v(:)),p(:))

No comments: