How to generate specific number of specific integers within a range?

1 vue (au cours des 30 derniers jours)
Doobie
Doobie le 27 Avr 2017
Commenté : Doobie le 28 Avr 2017
I want to generate a random array of 8 integers within [1,4] where each integer appears exactly twice. Examples:
1 1 2 2 3 3 4 4
4 2 1 2 3 1 3 4
2 4 1 2 3 4 3 1
I know randi(4,8,1) gives a random array of 8 integers within [1,4] but it does not specify how many come from which integer. Is there a built in matlab function that does this? If not, what should I do?

Réponse acceptée

Stephen23
Stephen23 le 28 Avr 2017
Modifié(e) : Stephen23 le 28 Avr 2017
This is easy with randperm:
>> vec = repmat(1:4,1,2);
>> out = vec(randperm(numel(vec)))
out =
2 3 2 4 1 1 4 3
>> out = vec(randperm(numel(vec)))
out =
1 4 2 3 2 1 3 4
>> out = vec(randperm(numel(vec)))
out =
2 1 2 4 3 3 4 1

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by