废话不多说,直接上代码
function [xt,yt,r,a] = Leastsquarecirclefitting(x,y)
%本方法用最小二乘法拟合圆;
%注意:需要新建.m文件引用Leastsquarecirclefitting函数
%Matlab程序中,x为需要拟合的点集的横坐标向量;y为需要拟合的点集的纵坐标向量(需要自己给出)
%(xt,yt)为拟合圆圆心坐标;
%r为拟合圆半径;
m=length(x);
xx=x.*x;
yy=y.*y;
xy=x.*y;
A=[sum(x) sum(y) m;sum(xy) sum(yy)...
sum(y);sum(xx) sum(xy) sum(x)];
B=[-sum(xx+yy) ; -sum(xx.*y+yy.*y) ; -sum(xx.*x+xy.*y)];
a=A\B;
xt = -.5*a(1);
yt = -.5*a(2);
r = sqrt((a(1)^2+a(2)^2)/4-a(3));
theta=0:0.1:2*pi;
Circle1=xt+r*cos(theta);
Circle2=yt+r*sin(theta);
plot(Circle1,Circle2,'g','linewidth',1);
axis equal
end
|