MATLAB Answers

Replacing 2 elements with each other randomly?

3 views (last 30 days)
IBM watson
IBM watson on 22 Oct 2018
Commented: the cyclist on 22 Oct 2018
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.

  0 Comments

Sign in to comment.

Accepted Answer

the cyclist
the cyclist on 22 Oct 2018
a = [2 4 5 242 24];
r = randperm(length(a));
b = a;
b([r(1) r(2)]) = a([r(2) r(1)]);

  2 Comments

the cyclist
the cyclist on 22 Oct 2018
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)

Sign in to comment.

More Answers (0)


Translated by