user1723765
user1723765

Reputation: 6409

Generate random number between 1 and 10 with the exception of a single number in matlab

I would like to generate a random number between 1 and 10 using for example randi([1,10]) but I would like to exclude a single number, say 7 - this number would always change and be specified in a variable called b.

Is that possible to do somehow?

Upvotes: 12

Views: 9360

Answers (3)

Dan
Dan

Reputation: 45752

For those without the statistics toolbox:

b = 7;
pop = 1:10;
pop(b) = [];

then

pop(randperm(9,1))

or for n random integers from the population:

pop(randi(numel(pop), 1, n))

Upvotes: 5

Roney Michael
Roney Michael

Reputation: 3994

As @EitanT mentioned, you can use randsample to do so, but I think that doing so in a simpler manner should do for you:

>> b = 7;
>> randsample([1:b-1,b+1:10],1)

This simply samples a random value from the array [1:b-1,b+1:10] which would here be

1     2     3     4     5     6     8     9    10

Or similarly, if the `randsample' function is unavailable as @EitanT had mentioned,

v = [1:b-1,b+1:10];
x = v(ceil(numel(v) * rand));

Upvotes: 1

Eitan T
Eitan T

Reputation: 32930

Use randsample. For instance, to generate a number between 1 and 10, excluding 7, do the following:

b = 7;
x = randsample(setdiff(1:10, b), 1);

Here setdiff is used to exclude the value of b from the vector 1:10.

If you don't have the Statistics Toolbox installed, you won't be able to use randsample, so use rand:

v = setdiff(1:10, b);
x = v(ceil(numel(v) * rand));

Upvotes: 18

Related Questions