没有例子很难回答,但听起来你只是想执行一个蒙特卡罗模拟 http://en.wikipedia.org/wiki/Monte_Carlo_method?
假设你的形状是由函数定义的f
并且您将 X、Y 限制存储在两个元素向量中,例如xlim = [-10 10] 即该形状的所有可能的 x 值都位于 x = -10 和 x = 10 之间,那么我建议您f
如果特定 x-y 对没有值,则返回某种错误代码。我假设那将是NaN
. So f(x,y)
是您正在编写的函数,它返回一个z
如果可以的话或者NaN
如果不能
n= 10000;
counter = 1;
shape = nan(n, 3)
while counter < n
x = rand*diff(xlim) + mean(xlmin);
y = rand*diff(ylim) + mean(ylim);
z = f(x,y)
if ~isnan(z)
shape(counter, :) = [x, y, z];
counter = counter + 1
end
end
因此,上面的代码将生成 10000 个(非唯一的,但很容易适应)在形状上随机采样的点。
现在,输入此内容后,我意识到也许您的形状实际上并不是那么大,也许您可以对其进行统一采样,而不是随机采样:
for x = xlim(1):xstep:xlim(2)
for y = ylim(1):ystep:ylim(2)
shape(counter, :) = [x, y, f(x,y)];
end
end
或者如果你写f
向量化(最好)
shape = [(xlim(1):xstep:xlim(2))', (ylim(1):ystep:ylim(2))', f(xlim(1):xstep:xlim(2), ylim(1):ystep:ylim(2));
然后无论哪种方式
shape(isnan(shape(:, 3), :) = []; %remove the points that fell outside the shape