Shuffle identical values of an array together

2 次查看(过去 30 天)
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 个评论
Jan
Jan 2021-2-5
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
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?

请先登录,再进行评论。

采纳的回答

Jan
Jan 2021-2-5
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);

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by