Shuffle identical values of an array together

조회 수: 3 (최근 30일)
Amirhossein Moosavi
Amirhossein Moosavi 2021년 2월 5일
답변: Jan 2021년 2월 5일
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
Amirhossein Moosavi 2021년 2월 5일
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