我目前有以下功能,但是有没有更有效的方法来生成一个范围内的随机整数并在 Matlab 中排除特定整数?
function aNew = random(a)
aMin = a-100;
aMax = a+100;
aNew = a;
while aNew == a
aNew = randi([aMin, aMax]);
end
为什么不做这样的事情:
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
您当前的方法进行拒绝抽样。你为什么不这样做:假设你要从中抽取样本的整数范围是[a, c]
,而你要排除的数字是b
。然后[a, c-1]
对每个大于或等于 的样本进行采样,并将b
其递增 1。
您可以使用该函数randsample
从指定分布中抽取样本。
像这样的东西应该可以正常工作
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
更新
如果您想从总体中排除多个值,您可以使用该setdiff
函数。
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
按照@slayton 的解决方案,为了对样本进行统一抽样N
,有放回,您可以在值总体内随机索引,有放回:
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