Count the adjacent same elements in a vector
조회 수: 8 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
채택된 답변
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)
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
추가 답변 (1개)
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)
참고 항목
카테고리
Help Center 및 File Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!