How to sum repeated adjacent values in a vector

7 ビュー (過去 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 Center および File ExchangeInteractive Control and Callbacks についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by