Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 994
user1723765 Avatar asked Apr 17 '13 08:04

user1723765


3 Answers

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));
like image 63
Eitan T Avatar answered Oct 17 '22 02:10

Eitan T


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))
like image 5
Dan Avatar answered Oct 17 '22 00:10

Dan


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));
like image 1
Roney Michael Avatar answered Oct 17 '22 01:10

Roney Michael