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?
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));
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))
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With