MATLAB: Shuffle identical values of an array together

MATLABunique

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

Best Answer

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);