How To Generate Non Repeating Random Numbers from 1 to 49

497 次查看(过去 30 天)
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

采纳的回答

Wayne King
Wayne King 2013-4-9
p = randperm(49);
p = p(1:10);
Or just
p = randperm(49,10);
  4 个评论
Samiu Haque
Samiu Haque 2020-9-9
What if it doesn't start with 1
For example:
Not repeating 10 random numbers in between 20 to 50
Steven Lord
Steven Lord 2020-9-9
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)

请先登录,再进行评论。

更多回答(1 个)

Niraj Dalal
Niraj Dalal 2019-8-9
p = randperm(49,10);

Community Treasure Hunt

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

Start Hunting!

Translated by