我有一组三维点(x,y,z),我想用最小绝对偏差方法对这些数据拟合一条直线。
我从互联网上找到了一个可以很好地处理2D数据的函数,我如何修改它以适应3D数据点?
function B = L1LinearRegression(X,Y)
% Determine size of predictor data
[n m] = size(X);
% Initialize with least-squares fit
B = [ones(n,1) X] \ Y;
% Least squares regression
BOld = B;
BOld(1) = BOld(1) + 1e-5;
% Force divergence
% Repeat until convergence
while (max(abs(B - BOld)) > 1e-6) % Move old coefficients
BOld = B; % Calculate new observation weights (based on residuals from old coefficients)
W = sqrt(1 ./ max(abs((BOld(1) + (X * BOld(2:end))) - Y),1e-6)); % Floor to avoid division by zero
% Calculate new coefficients
B = (repmat(W,[1 m+1]) .* [ones(n,1) X]) \ (W .* Y);
end非常感谢!
发布于 2016-03-16 21:24:56
我知道这不是对问题的回答,而是对导致问题的不同问题的回答。
我们可以多次使用fit函数。
% XYZ=[x(:),y(:),z(:)]; % suppose we have data in this format
M=size(XYZ,1); % read size of our data
t=((0:M-1)/(M-1))'; % create arbitrary parameter t
% fit all coordinates as function x_i=a_i*t+b_i
fitX=fit(t,XYZ(:,1),'poly1');
fitY=fit(t,XYZ(:,2),'poly1');
fitZ=fit(t,XYZ(:,3),'poly1');
temp=[0;1]; % define the interval where the line shall be plotted
%Evaluate and plot the line coordinates
Line=[feval(fitX(temp)),feval(fitY(temp)),feval(fitZ(temp))];
plot(Line)优点是,这适用于任何云,即使它平行于任何轴。另一个优点是,您不限于仅限于一阶多项式,您可以为不同的轴选择任何函数,并拟合任何3D曲线。
https://stackoverflow.com/questions/35988324
复制相似问题