random permutation with no matches to the position

2 vues (au cours des 30 derniers jours)
Valeria
Valeria le 25 Fév 2016
Commenté : Valeria le 25 Fév 2016
Hello everyone,
I have a question. When using randperm function I would like to get only those permutations where no i number appears on the position i in the vector. Does anybody have a suggestion on how to do so?
Example: 1 2 3 4 5
acceptable permutation: 3 1 5 2 4
non-acceptable permutation: 1 3 5 2 4
Thanks a lot in advance!
  2 commentaires
Stephen23
Stephen23 le 25 Fév 2016
Modifié(e) : Stephen23 le 25 Fév 2016
Brute force derangement:
N = 9;
out = randperm(N);
while any(out==(1:N))
out = randperm(N);
end
Valeria
Valeria le 25 Fév 2016
great, thanks!

Connectez-vous pour commenter.

Réponse acceptée

Torsten
Torsten le 25 Fév 2016
Modifié(e) : Torsten le 25 Fév 2016

Plus de réponses (1)

Jos (10584)
Jos (10584) le 25 Fév 2016
Modifié(e) : Jos (10584) le 25 Fév 2016
This specific type of permutation is called a derangement, and there are many methods to generate one. However, it is no so easy to come up with an elegant and fast algorithm.
There are several implementations on the file exchange. I will promote my own ;-) http://www.mathworks.com/matlabcentral/fileexchange/30189-randpermfull

Catégories

En savoir plus sur Random Number Generation dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by