Shuffling numbers while keeping identical numbers next to each other

1 view (last 30 days)
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

Accepted Answer

Stephen23
Stephen23 on 8 Jul 2020
Edited: Stephen23 on 8 Jul 2020
>> 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 Comments
Amirhossein Moosavi
Amirhossein Moosavi on 8 Jul 2020
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 on 8 Jul 2020
Edited: Stephen23 on 8 Jul 2020
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);

Sign in to comment.

More Answers (0)

Categories

Find more on Arithmetic Operations in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!