idealistikz
idealistikz

Reputation: 1267

What is the best way to generate a random integer within a range and exclude a specific integer in Matlab?

I currently have the following function, but is there a more efficient way to generate a random integer within a range and exclude a specific integer in Matlab?

function aNew = random(a)
aMin = a-100;
aMax = a+100;
aNew = a;
while aNew == a
    aNew = randi([aMin, aMax]);
end

Upvotes: 0

Views: 1242

Answers (4)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38042

Why not do something like this:

function aNew = random(a, sz)

    if nargin == 1, sz = [1 1]; end

    aMin = a-100;
    aMax = a+100;

    aNew = randi([aMin aMax-1], sz);

    aNew(aNew == a) = aMax;

end

Upvotes: 1

slayton
slayton

Reputation: 20319

You can use the function randsample to draw samples from a specified distribution.

Something like this should work fine

sampleRange = [1, 100];  % sample from 1 to 100
noSample = 50; % lets exclude 50
pop2Sample = [range(1):noSample-1, noSample+1:range(2)]; %create the population

sample = randsample(pop2Sample,1); %draw a single sample

Update

If you wanted to exclude multiple values from your population you could use the setdiff function.

pop2Sample = 1:100;  % sample from 1 to 100
noSample = 0:10:100 % lets exclude any all multiples of ten
pop2Sample = setdiff(pop2Sample, noSample);

sample = randsample(pop2Sample,1); %draw a single sample

Upvotes: 1

gevang
gevang

Reputation: 5014

Along the lines of @slayton 's solution, for uniform sampling on N samples, with replacement, you can randomly index, with replacement, inside the value population:

N = 10; % samples
aMin = -100; % lower
aMax = +100; % upper
a = 0; % excluded int 

valPop = [aMin:a-1, a+1:aMax]; % value population
samples = valPop(randi([1, N-1], 1, N)); % with resampling

Upvotes: 0

Ansari
Ansari

Reputation: 8218

Your current method does rejection sampling. Why don't you do this: Suppose the range of integers you want to draw samples from is [a, c] and the number you want to exclude is b. Then sample from [a, c-1] and for every sample larger than or equal to b, increment it by 1.

Upvotes: 1

Related Questions