Azzera filtri
Azzera filtri

Shuffle identical values of an array together

1 visualizzazione (ultimi 30 giorni)
Hi,
Let us suppose arrays A and B:
A = [1 9 6 2 10 8 3 8 11 7 5 5 6]
B = [1 2 2 1 1 1 1 1 2 2 2 2 2]
I want to create an array C that randomly puts all element of array A with identical values in array B together (with out chanding the order of identical elements in array A). For example, the array C can be as follows:
C = [1 2 10 8 3 8 9 6 11 7 5 5 6]
C = [9 6 11 7 5 5 6 1 2 10 8 3 8]
% where the first group with identical values in B is [1 2 10 8 3 8]
% and the second group is [9 6 11 7 5 5 6]
Now, let me clarify how the array C can be generated. First, I need to detect the uniqe values in the array B, which will be:
D = [1 2]
Then, I need to randomly sort the array D. Then, I will use the elements in sorted D to generate the array C as follows:
C = [A(B == D(1)) A(B == D(2))]
What would be the most efficient way for doing this action?
Many thanks for your attention, Amirhossein
  2 Commenti
Jan
Jan il 5 Feb 2021
I do not understand, how C is created. At first I thought, you want to shuffle the elements of A on the positions B==1, and in the next step at B==2, but this does not match the both examples C.
The first C can create by:
A = [1 9 6 2 10 8 3 8 11 7 5 5 6]
B = [1 2 2 1 1 1 1 1 2 2 2 2 2]
C = [A(B==1), A(B==2)]
But this is not random. So please explain again, what you exactly want.
Amirhossein Moosavi
Amirhossein Moosavi il 5 Feb 2021
Thanks for the question! Let me clarify by how the array C can be generated. First, I need to detect the uniqe values in the array B, which will be:
D = [1 2]
Then, I need to randomly sort the array D. Then, I will use the elements in sorted D to generate the array C as follows:
C = [A(B == D(1)) A(B == D(2))]
Is it clear now?

Accedi per commentare.

Risposta accettata

Jan
Jan il 5 Feb 2021
A = [1 9 6 2 10 8 3 8 11 7 5 5 6]
B = [1 2 2 1 1 1 1 1 2 2 2 2 2]
uB = unique(B);
nuB = numel(uB);
uB = uB(randperm(nuB));
C = [A(B == uB(1)), A(B == uB(2))];
I guess, that B can have an arbitrary number of elements. Then:
A = [1 9 6 2 10 8 3 8 11 13 7 5 5 6 14 15]
B = [1 2 2 1 1 1 1 1 2 3 2 2 2 2 3 3 ]
uB = unique(B);
LUT = randperm(numel(uB));
BB = LUT(B - min(B) + 1);
[~, index] = sort(BB);
D = A(index);

Più risposte (0)

Categorie

Scopri di più su Shifting and Sorting Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by