How to sum repeated adjacent values in a vector

조회 수: 6 (최근 30일)
Galgool
Galgool 2019년 4월 27일
댓글: Galgool 2019년 4월 28일
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 ) ;
  댓글 수: 2
Andrei Bobrov
Andrei Bobrov 2019년 4월 27일
+1.
accumarray(cumsum(diff([0;X(:)])~=0),X(:));
Galgool
Galgool 2019년 4월 28일
it does the job. thanks.

댓글을 달려면 로그인하십시오.

카테고리

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