Shuffling numbers while keeping identical numbers next to each other

조회 수: 1 (최근 30일)
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

채택된 답변

Stephen23
Stephen23 2020년 7월 8일
편집: Stephen23 2020년 7월 8일
>> 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
Amirhossein Moosavi
Amirhossein Moosavi 2020년 7월 8일
Thanks! It works. One more question. What if I have another array (identical size) and want to shuffle it with the exact same order? For example:
A = [1 1 2 3 3 4 6 6 6 6]
B = [1 2 3 4 5 6 7 8 9 10]
Now, assume that I have shffuled A as follows:
A = [6 6 6 6 1 1 2 3 3 4]
Accordingly, array B must be sorted as follows:
B = [7 8 9 10 1 2 3 4 5 6]
Thanks in advance!
Stephen23
Stephen23 2020년 7월 8일
편집: Stephen23 2020년 7월 8일
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);

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Arithmetic Operations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by