Shuffling numbers while keeping identical numbers next to each other

1 回表示 (過去 30 日間)
Amirhossein Moosavi
Amirhossein Moosavi 2020 年 7 月 8 日
編集済み: Stephen23 2020 年 7 月 8 日
Hi everyone,
Let us assume the following array:
A = [1 1 2 3 3 4 6 6 6 6]
I would like to shuffle this array while while keeping identical numbers next to each other (e.g., array B):
B = [1 1 3 3 6 6 6 6 4 2]
This means that array C is not desirable for me:
C = [1 3 1 3 6 4 6 2 6 6]
Do you have any suggestion?
Regards,
Amir

採用された回答

Stephen23
Stephen23 2020 年 7 月 8 日
編集済み: Stephen23 2020 年 7 月 8 日
>> A = [1,1,2,3,3,4,6,6,6,6];
>> X = diff(find([1,diff(A),1]));
>> C = mat2cell(A,1,X);
>> Y = randperm(numel(C));
>> V = [C{Y}]
V = 2 1 1 6 6 6 6 3 3 4
  2 件のコメント
Amirhossein Moosavi
Amirhossein Moosavi 2020 年 7 月 8 日
Thanks! It works. One more question. What if I have another array (identical size) and want to shuffle it with the exact same order? For example:
A = [1 1 2 3 3 4 6 6 6 6]
B = [1 2 3 4 5 6 7 8 9 10]
Now, assume that I have shffuled A as follows:
A = [6 6 6 6 1 1 2 3 3 4]
Accordingly, array B must be sorted as follows:
B = [7 8 9 10 1 2 3 4 5 6]
Thanks in advance!
Stephen23
Stephen23 2020 年 7 月 8 日
編集済み: Stephen23 2020 年 7 月 8 日
To sort the 2nd vector into the same order you could split and recombine just like we did for the 1st, e.g.:
D = mat2cell(B,1,X);
Bout = [D{Y}]
But if you need to do this for quite a few vectors, simply generate the indices:
D = mat2cell(1:numel(A),1,X);
Z = [D{Y}];
and then use those indices as often as required:
Bout = B(Z);

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeArithmetic Operations についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by