Shuffling numbers while keeping identical numbers next to each other

1 次查看(过去 30 天)
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
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 CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by