Shuffling numbers while keeping identical numbers next to each other
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Amirhossein Moosavi
le 8 Juil 2020
Modifié(e) : Stephen23
le 8 Juil 2020
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
0 commentaires
Réponse acceptée
Stephen23
le 8 Juil 2020
Modifié(e) : Stephen23
le 8 Juil 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 commentaires
Stephen23
le 8 Juil 2020
Modifié(e) : Stephen23
le 8 Juil 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);
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrices and Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!