Replacing 2 elements with each other randomly?

조회 수: 1 (최근 30일)
IBM watson
IBM watson 2018년 10월 22일
댓글: the cyclist 2018년 10월 22일
Like : a=[2 4 5 242 24] ------> a'=[2 242 5 4 24]
my code is :
rndm= myset(randperm(length(myset),2))
neighbor=myset;
dummy=myset(rndm(1));
neighbor(rndm(1))= myset(rndm(2));
neighbor(rndm(2))=dummy
It is working but sometimes i get out of bounds error. Because the myset vector includes elements like 234. If big numbers elements (like 242) have chosen by randomly then rndm(1) will be equal to 242. So myset(242) is out of bounds for sure.

채택된 답변

the cyclist
the cyclist 2018년 10월 22일
a = [2 4 5 242 24];
r = randperm(length(a));
b = a;
b([r(1) r(2)]) = a([r(2) r(1)]);
  댓글 수: 2
IBM watson
IBM watson 2018년 10월 22일
Thanks!
the cyclist
the cyclist 2018년 10월 22일
I didn't look at your solution carefully, but it looks like the only essential difference is that you did
rndm = myset(randperm(length(myset),2))
where you should have done just
rndm = randperm(length(myset),2)

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by