How To Generate Non Repeating Random Numbers from 1 to 49
114 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi,
Does anybody know how to generate a series of 10 non-repeating random integers between 1 and 49?
So far I've tried using p = randperm(50); p = p(1:10)-1; but this can give me 0 in my series of 10 random integers :/
Thanks
0 commentaires
Réponse acceptée
Wayne King
le 9 Avr 2013
p = randperm(49);
p = p(1:10);
Or just
p = randperm(49,10);
4 commentaires
Samiu Haque
le 9 Sep 2020
What if it doesn't start with 1
For example:
Not repeating 10 random numbers in between 20 to 50
Steven Lord
le 9 Sep 2020
Generate 10 random numbers in the interval [1, 31] (31 being the number of elements in the vector 20:50) and either add 19 or use them as indices into 20:50.
The former approach avoids explicitly creating the vector 20:50 (not a big deal for this example, a big deal if you're trying to select 10 elements from a very large range of values whose length you know.)
% Select 10 numbers from 100 to 1e7 without explicitly creating 100:1e7
UL = 1e7;
LL = 100;
numElements = UL-LL+1;
r = randperm(numElements, 10);
r + LL
The latter can be used even when the vector you're trying to sample has "holes" like the following.
x = 1:50;
x(mod(x, 5) == 0) = []
ind = randperm(numel(x), 6)
x(ind)
Plus de réponses (1)
Voir également
Catégories
En savoir plus sur Logical 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!