Reducing repeated elements in an array by a factor

2 ビュー (過去 30 日間)
Thomas Gvero
Thomas Gvero 2020 年 2 月 12 日
回答済み: Matt J 2020 年 2 月 12 日
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 件のコメント
Matt J
Matt J 2020 年 2 月 12 日
編集済み: Matt J 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
Thomas Gvero 2020 年 2 月 12 日
As far as I'm aware, in the context i am using it, yes.

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

採用された回答

Stephen23
Stephen23 2020 年 2 月 12 日
編集済み: Stephen23 2020 年 2 月 12 日
>> V = [1,2,2,2,2,2,2,5,6];
>> N = 3;
>> X = cumsum([1,diff(V)~=0]);
>> F = @(v) {v(1:ceil(numel(v)/N))};
>> cell2mat(accumarray(X(:),V(:),[],F))
ans =
1
2
2
5
6
  1 件のコメント
Thomas Gvero
Thomas Gvero 2020 年 2 月 12 日
thank you so much!

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

その他の回答 (1 件)

Matt J
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

カテゴリ

Help Center および File ExchangeCell Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by