MATLAB Answers

Galgool
0

How to sum repeated adjacent values in a vector

Asked by Galgool
on 27 Apr 2019
Latest activity Commented on by Galgool
on 28 Apr 2019
Hi guys,
I have a random vector with -1 and 1.
for example:
X = [1, 1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, 1, -1, -1]
I wish to creat a vector that sums repeated adjacent values.
so for the above example:
Y = [2, -1, 3, -2, 1, -1, 4, -2]
any idea?

  0 Comments

Sign in to comment.

Tags

1 Answer

Answer by Cedric Wannaz
on 27 Apr 2019
Edited by Cedric Wannaz
on 27 Apr 2019

Here is one way:
Y = splitapply( @sum, X, [0, cumsum( diff(X) ~= 0 )] + 1 ) ;
or, split into two expressions that make it easier to understand:
groupId = [0, cumsum( diff(X) ~= 0 )] + 1 ;
Y = splitapply( @sum, X, groupId ) ;

  2 Comments

+1.
accumarray(cumsum(diff([0;X(:)])~=0),X(:));
it does the job. thanks.

Sign in to comment.