简体   繁体   中英

How to plot a circle in Matlab? (least square)

I am trying to plot a circle's equation-regression on x and y, but I do not know how to proceed. Any suggestions? (I want a circle to connect the points thru least square solution)

x = [5; 4; -1; 1];
y = [3; 5; 2; 1];

% circle's equation: x^2+y^2 = 2xc1+2yc2+c3
a = [2.*x,2.*y,ones(n,3)]
b = [x.^2 + y.^2];
c = a\b;

How do I plot the circle after this

There are a couple of ways how to plot a circle in matlab:

  • plot a line where the data points form a circle
  • use the 'o' marker in plot and the 'MarkerSize' name-value pair to set the radius of the circle
  • you can plot a circle image using the vscircle function In your case, I would go with the first option, since you maintain in control of the circle size.
  • use the rectangle(...,'Curvature',[1 1]) function [EDITED: thx to @Cris Luengo]

So here is a plotting function

function circle(x,y,r)
%x and y are the coordinates of the center of the circle
%r is the radius of the circle
%0.01 is the angle step, bigger values will draw the circle faster but
%you might notice imperfections (not very smooth)
ang=0:0.01:2*pi+.01; 
xp=r*cos(ang);
yp=r*sin(ang);

plot(x+xp,y+yp);
end

So with your (corrected) code, it looks like this

x = [5; 4; -1; 1];
y = [3; 5; 2; 1];

% circle's equation:  x^2+y^2 = 2xc1+2yc2+c3
a = [2.*x,2.*y,ones(length(x),1)];
b = [x.^2 + y.^2];
c = a\b;

x_m = c(1)/2;
y_m = c(2)/2;
r = sqrt(x_m^2 + y_m^2 -c(3));

% plot data points
plot(x,y,'o')
hold on
% plot center
plot(x_m,y_m,'+')
% plot circle
circle(x_m,y_m,r)
hold off

MATLAB 图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM