Shuffling numbers while keeping identical numbers next to each other

1 Ansicht (letzte 30 Tage)
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

Akzeptierte Antwort

Stephen23
Stephen23 am 8 Jul. 2020
Bearbeitet: Stephen23 am 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 Kommentare
Amirhossein Moosavi
Amirhossein Moosavi am 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 am 8 Jul. 2020
Bearbeitet: Stephen23 am 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);

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Arithmetic Operations finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by