Reducing repeated elements in an array by a factor
이전 댓글 표시
Is there a way to reduce the number of repeated elements in an array by a factor? For example, say the factor I had was 3, i would want to reduce
[1 2 2 2 2 2 2 5 6]
to
[1 2 2 5 6]
i.e. only leave one third of the repeated elements.
Not sure if this is possible but worth a shot, thanks! :)
댓글 수: 4
Stephen23
2020년 2월 12일
How do you count "repeats": only contiguous repeats or any repeats throughout the entire vector?
I.e. does this count as two independent groups of 2, or do they all get counted together?:
[1,2,2,2,0,2,2,2,5,6]
Thomas Gvero
2020년 2월 12일
Do the repeated elements always occur in fixed, known multiples? How would, a reduction by 3 handle this,
[1 1 1 5 2 2 2 2 6]
Thomas Gvero
2020년 2월 12일
채택된 답변
추가 답변 (1개)
Matt J
2020년 2월 12일
Another method, one which avoids for-loops inherent in cell2mat,
V=[1,2,2,2,0,2,2,2,5,5,5,5,5,5,6,6,6];
N=3;
X = cumsum([1,diff(V)~=0]);
[~,idx]=unique([X,inf],'stable');
result=V( repelem(idx(1:end-1), ceil(diff(idx)/N) ) )
result =
1 2 0 2 5 5 6
카테고리
도움말 센터 및 File Exchange에서 Cell Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!