How To Generate Non Repeating Random Numbers from 1 to 49

1.104 views (last 30 days)
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

Accepted Answer

Wayne King
Wayne King on 9 Apr 2013
p = randperm(49);
p = p(1:10);
Or just
p = randperm(49,10);
  4 Comments
Steven Lord
Steven Lord on 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)

Sign in to comment.

More Answers (1)

Niraj Dalal
Niraj Dalal on 9 Aug 2019
p = randperm(49,10);

Categories

Find more on Random Number Generation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!