Borrar filtros
Borrar filtros

How to sum repeated adjacent values in a vector

5 visualizaciones (últimos 30 días)
Galgool
Galgool el 27 de Abr. de 2019
Comentada: Galgool el 28 de Abr. de 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?

Respuestas (1)

Cedric
Cedric el 27 de Abr. de 2019
Editada: Cedric el 27 de Abr. de 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 comentarios
Andrei Bobrov
Andrei Bobrov el 27 de Abr. de 2019
+1.
accumarray(cumsum(diff([0;X(:)])~=0),X(:));
Galgool
Galgool el 28 de Abr. de 2019
it does the job. thanks.

Iniciar sesión para comentar.

Categorías

Más información sobre Interactive Control and Callbacks en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by