draw circle in matlab and generate random coordinate inside the circle and the negative of the coordinate

StackOverflow https://stackoverflow.com/questions/22565459

I am required to plot a circle in matlab and mark its center and generate a random coordinate inside the circle and the negative of this coordinate and measure the distance between these two points I tried this

x = linspace(-sqrt(10),sqrt(10));
y1 = sqrt(10-x.^2);
y2 = -sqrt(10-x.^2);
plot(x,y1,x,y2)
axis equal

to make the circle and its ok but i don't know how to proceed to generate the random coordinate ad its negative and measure the distance between them

有帮助吗?

解决方案

Add this to your code -

%%// Choose from 100 random point pairs
N = 100; 
%%// Radius of circle
radius = sqrt(10); 

%%// Create a random point matrix Nx2
pt1 = [ radius*2*(rand(N,1)-0.5) radius*2*(rand(N,1)-0.5)];

%%// Select the first pair that lies inside circle
pt1 = pt1(find(sqrt( pt1(:,1).^2 + pt1(:,2).^2 )<radius,1),:);

%%// Negative of the point, i.e. on the other side of the center of the circle but equidistant from the center
pt2 = -pt1;

%%// Distance between the two points
dist1 = sqrt((pt1(1)-pt2(1)).^2 + (pt1(2)-pt2(2)).^2); 

%%// Overlay the center and the two points on the circle plot
hold on
text(0,0,'C') %%// Center
text(pt1(1),pt1(2),'P') %%// First point
text(pt2(1),pt2(2),'MP') %%// Second point (Mirror Point, MP)

Plot

enter image description here

其他提示

You can use the rand() function to produce a random distance from center, as well as to produce a random angle. You can then convert to x,y coordinates, and negate them to get the negative coordinates. Finally, you can use the distance formula to calculate the distance between the two coordinates. Here is some sample code:

x = linspace(-sqrt(10),sqrt(10));
y1 = sqrt(10-x.^2);
y2 = -sqrt(10-x.^2);
plot(x,y1,x,y2)
axis equal
hold on

r_max = sqrt(10); %set to radius of circle

r = rand(1)*r_max; %produces a random vector whose length is <=radius
theta = rand(1)*2*pi; % produces a random angle

x_coord = r*cos(theta); %calculate x coord
y_coord = r*sin(theta); % calculate y coord

x_coord_neg = -1*x_coord; % negate x coord
y_coord_neg = -1*y_coord; % negate y coord

plot(x_coord,y_coord, 'x')
plot(x_coord_neg,y_coord_neg, 'rx')

dist = sqrt((x_coord - x_coord_neg)^2 +  (y_coord - y_coord_neg)^2) % calculate distance

Not sure if you actually want "negative coordinates" or the complex conjugate of the coordinates. In the case of the latter, you would just negate y to get the complex conjugate.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top