利用Matlab实现直线和平面的拟合

直线和平面拟合是很常用的两个算法,原理非常简单。但如果matlab不太熟的话,写起来也不是那么容易。搜了很久才找到这两个代码,保存之,免得日后麻烦。
1、直线拟合的matlab代码
% Fitting a best-fit line to data, both noisy and non-noisyx = rand(1,10);n = rand(size(x)); % Noisey = 2*x + 3; % x and y satisfy y = 2*x + 3yn = y + n; % x and yn roughly satisfy yn = 2*x + 3 due to the noise% Determine coefficients for non-noisy line y=m1*x+b1Xcolv = x(:); % Make X a column vectorYcolv = y(:); % Make Y a column vectorConst = _disibledevent=>m1 = Coeffs(1);b1 = Coeffs(2);% To fit another function to this data, simply change the first % matrix _disibledevent=>% Coeffs = [Xcolv.^2 Xcolv Const]\Ycolv; % Note the .^ before the exponent of the first term% Plot the original points and the fitted curvefigureplot(x,y,'ro')hold _disibledevent=>y2 = m1*x2+b1; % Evaluate fitted curve at many pointsplot(x2, y2, 'g-')title(sprintf('Non-noisy data: y=%f*x+%f',m1,b1))% Determine coefficients for noisy line yn=m2*x+b2Xcolv = x(:); % Make X a column vectorYncolv = yn(:); % Make Yn a column vectorConst = _disibledevent=>m2 = NoisyCoeffs(1);b2 = NoisyCoeffs(2);% Plot the original points and the fitted curvefigureplot(x,yn,'ro')hold _disibledevent=>yn2 = m2*x2+b2;plot(x2, yn2, 'g-')title(sprintf('Noisy data: y=%f*x+%f',m2,b2))
2、平面拟合matlab代码
x = rand(1,10);y = rand(1,10);z = (3-2*x-5*y)/4; % Equation of the plane containing % (x,y,z) points is 2*x+5*y+4*z=3Xcolv = x(:); % Make X a column vectorYcolv = y(:); % Make Y a column vectorZcolv = z(:); % Make Z a column vectorConst = _disibledevent=>XCoeff = Coefficients(1); % X coefficientYCoeff = Coefficients(2); % X coefficientCCoeff = Coefficients(3); % constant term% Using the above variables, z = XCoeff * x + YCoeff * y + CCoeffL=plot3(x,y,z,'ro'); % Plot the original data pointsset(L,'Markersize',2*get(L,'Markersize')) % Making the circle markers largerset(L,'Markerfacecolor','r') % Filling in the markershold _disibledevent=>zz = XCoeff * xx + YCoeff * yy + CCoeff;surf(xx,yy,zz) % Plotting the surfacetitle(sprintf('Plotting plane z=(%f)*x+(%f)*y+(%f)',XCoeff, YCoeff, CCoeff))% By rotating the surface, you can see that the points lie on the plane% Also, if you multiply both sides of the equation in the title by 4,% you get the equation in the comment on the third line of this example
Tags: 

延伸阅读

最新评论

发表评论