필터 지우기
필터 지우기

How to randomly swap 2 elements in an array?

조회 수: 2 (최근 30일)
Hang Vu
Hang Vu 2019년 5월 1일
댓글: Hang Vu 2019년 5월 8일
Suppose that I have the below array:
C= [1 6 5 10 1 2 11 8 2 7 3 7 9 9]
How can I swap randomly only the elements inside the bold numbers
Assume after swap 11 and 3 : C= [1 6 5 10 1 2 3 8 2 7 11 7 9 9]
or swap 10 and " " between 9 9: C= [1 6 5 1 2 11 8 2 7 3 7 9 10 9]

채택된 답변

Rik
Rik 2019년 5월 1일
편집: Rik 2019년 5월 1일
I'm going to assume at least one of the swap elements must be an number, and that the swapped numbers are allowed to have the same value (so you can some one 9 with another 9).
C= [1 6 5 10 1 2 11 8 2 7 3 7 9 9];
bold=[1 5 6 9 10 12 13 14];
C_temp=cell(1,2*numel(C));
C_temp(2:2:end)=num2cell(C);
valid_idx=1:numel(C_temp);
valid_idx(bold*2)=[];
swap_idx=[1 1];%invalid output to enter the loop
while ~any(mod(swap_idx,2)==0) || ... %at least 1 needs to be a number
swap_idx(1)==swap_idx(2) %the indices must be different
swap_idx=valid_idx(randperm(numel(valid_idx),2));
end
%perform swap
C_temp(swap_idx)=C_temp(swap_idx(end:-1:1));
D=cell2mat(C_temp);
clc,disp(C),disp(D)
  댓글 수: 12
Rik
Rik 2019년 5월 4일
This should prevent the two swapped values to be adjacent (which swaps a value with a gap, meaning it seems the array stays the same).
while ~any(mod(swap_idx,2)==0) || ... %at least 1 needs to be a number
any(swap_idx==1) || ... %the first element (1 before the first number) isn't allowed
abs(diff(swap_idx))<=1 %the indices must be different and more than 1 appart
swap_idx=valid_idx(randperm(numel(valid_idx),2));
end
Hang Vu
Hang Vu 2019년 5월 8일
Thank you for the help!

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by