How to sum repeated adjacent values in a vector

6 次查看(过去 30 天)
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?

回答(1 个)

Cedric
Cedric 2019-4-27
编辑:Cedric 2019-4-27
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 ) ;

类别

Help CenterFile Exchange 中查找有关 Interactive Control and Callbacks 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by