如何在椭圆matlab中绘制随机点

时间:2017-12-30 18:03:04

标签: matlab

我想用它内部的N个随机点填充这个椭圆 任何帮助我都很高兴

clear ,close all;
xCenter = 15;
yCenter = 10;
xRadius = 3.5;
yRadius = 8;
theta = 0 : 0.01 : 2*pi;
N = 100; % N rand points

x = xRadius * cos(theta) + xCenter;
y = yRadius * sin(theta) + yCenter;    

plot(x, y, 'LineWidth', 1);

axis square;

grid on;

我尝试使用特定参数在椭圆内生成100个点,但是我没有实现目标,

xCenter = 5;
yCenter = 3;
xRadius = 3.5;
yRadius = 8;
theta = 0 : 0.01 : 2*pi;
N = 100;

x = xRadius * cos(theta) + xCenter;
y = yRadius * sin(theta) + yCenter;

xq=(rand(N,1)*(2*yRadius) - yRadius);
yq=(rand(N,1)*(2*yRadius) - yRadius);    

in = inpolygon(xq,yq,x,y);
hold on
inX = xq(in);
inY = yq(in);
outX = xq(~in);
outY = yq(~in);
plot(inX, inY , 'ro');
plot(outX, outY, 'b*');
plot(x, y, 'LineWidth', 1);

axis square;

grid on;

2 个答案:

答案 0 :(得分:6)

Sardar的答案产生的点不均匀分布在椭圆内。此代码生成均匀的点分布:

xCenter = 15;
yCenter = 10;
xRadius = 3.5;
yRadius = 8;
N = 100;

% Generate points in the ellipse
t = 2*pi * rand(N,1);
d = sqrt(rand(N,1));
x = xCenter + xRadius * d .* cos(t);
y = yCenter + yRadius * d .* sin(t);
plot(x,y,'o')

差异是距离原点sqrt的标准化(0到1)距离上的d。通过计算此平方根,可以增加更接近椭圆边缘的点的密度。这补偿了在中心附近过于密集的点。沿着归一化距离的点的均匀分布是导致中心附近的点密度更高的原因。

答案 1 :(得分:2)

为各轴生成指定限制(即xRadiusyRadius)之间的x和y轴的随机数。阅读Random Numbers Within a Specific Range以了解如何生成这些随机数。

hold on;
RndAngles = rand(N,1);      %Same angle should be used
Xpoints = (xRadius.*rand(N,1) .*cos(2*pi*RndAngles))+ xCenter;   
Ypoints = (yRadius.*rand(N,1) .*sin(2*pi*RndAngles))+ yCenter;
plot(Xpoints,Ypoints,'o');  %Plot those points

<强> 输出:

Output