最小二乘法拟合圆公式推导及matlab实现
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
2009-01-17 | 最小二乘法拟合圆公式推导及matlab实现
最小二乘法(least squares analysis)是一种数学优化技术,它通过最小化误差的平方和找到一组数据的最佳函数匹配。最小二乘法是用最简的方法求得一些绝对不可知的真值,而令误差平方之和为最小。最小二乘法通常用于曲线拟合(least squares fitting) 。
这里有拟合圆曲线的公式推导过程和vc实现。
matlab 实现:
function[R,A,B]=irc(x,y,N)
%x,y是平面点的坐标,N是点个数
%R是拟合半径,A,B是圆心的平面坐标
x1=0;
x2=0;
x3=0;
y1=0;
y2=0;
y3=0;
x1y1=0;
x1y2=0;
x2y1=0;
for i=1:N
x1=x1+x(i);
x2=x2+x(i)*x(i);
x3=x3+x(i)*x(i)*x(i);
y1=y1+y(i);
y2=y2+y(i)*y(i);
y3=y3+y(i)*y(i)*y(i);
x1y1=x1y1+x(i)*y(i);
x1y2=x1y2+x(i)*y(i)*y(i);
x2y1=x2y1+x(i)*x(i)*y(i);
end
C=N*x2-x1*x1;
D=N*x1y1-x1*y1;
E=N*x3+N*x1y2-(x2+y2)*x1;
G=N*y2-y1*y1;
H=N*x2y1+N*y3-(x2+y2)*y1;
a=(H*D-E*G)/(C*G-D*D);
b=(H*C-E*D)/(D*D-G*C);
c=-(a*x1+b*y1+x2+y2)/N;
A=a/(-2);
B=b/(-2);
R=sqrt(a*a+b*b-4*c)/2;
VC
void CViewActionImageTool::LeastSquaresFitting() {
if (m_nNum<3)
{ return; }
int i=0;
double X1=0;
double Y1=0;
double X2=0;
double Y2=0;
double X3=0;
double Y3=0;
double X1Y1=0;
double X1Y2=0;
double X2Y1=0;
for (i=0;i { X1 = X1 + m_points[i].x; Y1 = Y1 + m_points[i].y; X2 = X2 + m_points[i].x*m_points[i].x; Y2 = Y2 + m_points[i].y*m_points[i].y; X3 = X3 + m_points[i].x*m_points[i].x*m_points[i].x; Y3 = Y3 + m_points[i].y*m_points[i].y*m_points[i].y; X1Y1 = X1Y1 + m_points[i].x*m_points[i].y; X1Y2 = X1Y2 + m_points[i].x*m_points[i].y*m_points[i].y; X2Y1 = X2Y1 + m_points[i].x*m_points[i].x*m_points[i].y; } double C,D,E,G,H,N; double a,b,c; N = m_nNum; C = N*X2 - X1*X1; D = N*X1Y1 - X1*Y1; E = N*X3 + N*X1Y2 - (X2+Y2)*X1; G = N*Y2 - Y1*Y1; H = N*X2Y1 + N*Y3 - (X2+Y2)*Y1; a = (H*D-E*G)/(C*G-D*D); b = (H*C-E*D)/(D*D-G*C); c = -(a*X1 + b*Y1 + X2 + Y2)/N; double A,B,R; A = a/(-2); B = b/(-2); R = sqrt(a*a+b*b-4*c)/2; m_fCenterX = A; m_fCenterY = B; m_fRadius = R; return;}