Count the adjacent same elements in a vector

9 ビュー (過去 30 日間)
ayça kepçe
ayça kepçe 2019 年 7 月 1 日
コメント済み: ayça kepçe 2019 年 7 月 9 日
Hello! Assume we have a vector of A=[1 1 1 2 2 3 3 3 3 3 1 1]. A has three 1, two 2, five 3 and two 1.
I need to create a vector, such as B=[3 2 5 2] and their corresponding value C=[1 2 3 1].
Maybe i should use a struct, not sure. Glad for some help :/
thx.

採用された回答

Matt J
Matt J 2019 年 7 月 1 日
編集済み: Matt J 2019 年 7 月 1 日
L=cumsum([1, diff(A)~=0]);
B=splitapply(@sum,ones(size(A)),L)
C=splitapply(@min,A,L)
  2 件のコメント
Jos (10584)
Jos (10584) 2019 年 7 月 1 日
Nice use of splitapply. Here is a simpler version of run-length encoding:
A=[1 1 1 2 2 3 3 3 3 3 1 1]
x = find([true diff(A)~=0])
B = diff([x numel(A)+1]) % run-lengths
C = A(x) % elements
ayça kepçe
ayça kepçe 2019 年 7 月 9 日
Thank you so much! But if i had seen it one week ago, i would not lost a week in a six week internship. Sometimes a tiny code piece like this saves the entire project...

サインインしてコメントする。

その他の回答 (1 件)

Jos (10584)
Jos (10584) 2019 年 7 月 1 日
This is call run-length encoding, for which you can find excellent function on the File exchange. For instance, [shameless self promotion ;-) ], this one: https://uk.mathworks.com/matlabcentral/fileexchange/56131-runindex
A = [1 1 1 2 2 3 3 3 3 3 1 1]
[~, RLE] = runindex(A)
B = RLE(:,3)
C = RLE(:,1)
  1 件のコメント
ayça kepçe
ayça kepçe 2019 年 7 月 9 日
I tried to write a loop of my own, but didnt work so well :) your function will be in mind for incase!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeString Parsing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by