用MATLAB中的lsqcurvefit求解一组超定方程

时间:2016-02-14 22:00:39

标签: matlab nonlinear-optimization

我遇到类似这个问题的问题: How to solve an overdetermined set of equations using non-linear lest squares in Matlab

我有9个方程,有2个未知数x和y,如下:

A11=(sin(x))*(cos(y))*(sin(x))*(cos(y));
A12=(sin(x))*(cos(y))*(sin(x))*(sin(y));
A13=(sin(x))*(cos(y))*(cos(x));
A21=(sin(x))*(sin(y))*(sin(x))*(cos(y));
A22=(sin(x))*(sin(y))*(sin(x))*(sin(y));
A23=(sin(x))*(sin(y))*(cos(x));
A31=(sin(x))*(cos(y))*(cos(x));
A32=(sin(x))*(sin(y))*(cos(x));
A33=(cos(x))*(cos(x));

我知道每个A_ij的值,并想要计算x和y。 我试图通过像这样使用lsqcurvefit来实现:

ydata=[0, 0, 0, 0, 1, 0, 0, 0, 0]; % this is one set of A_ij
lb=[0,0];
ub=[pi,2*pi];
x0=[pi/2;pi];
p=zeros(2,1);
p = lsqcurvefit( myfun,x0,xdata,ydata,lb,ub)

我没有xdata的任何值,所以有没有办法让它像这样运行? 我将函数myfun定义为:

function r = myfun(p)

x=p(1);
y=p(2);

The 9 equations;

r=[A11, A12, A13, A21, A22, A23, A31, A32, A33];
end

现在,每当我运行lsqcurvefit时,我都会收到错误“没有足够的输入参数”。并且错误发生在x = p(1)的行中; 我不知道缺少什么或更好,我不知道如何处理我没有xdata输入的事实。

我希望有人可以帮助我实现这个目标。 非常感谢你提前。

费边

1 个答案:

答案 0 :(得分:0)

经过一些修修补补后,我让它与lsqcurvefit合作。这基本上是我如何解决xdata和ydata到函数句柄的问题。 这就是我的代码最终的样子:

ydata = [0.12; 0.28; 0.16; 0.66; 0.38; 0.22];
xdata = [0; 0; 0; 0; 0; 0]; % just as a dummy, lsqcurvefit wants the input
x0=[0,0];
lb=[0,0];
ub=[180,180];
[x,resnorm,residual,exitflag,output] = lsqcurvefit(@fun,x0,xdata,ydata,lb,ub);
% only x is needed, but I used the other information for other parts of my code
% as a separate function.m file
function F = fun(x,xdata) % again, xdata is just a dummy and not used

p1=cosd(x(1));
p2=sind(x(1))*sind(x(2));
p3=sind(x(1))*cosd(x(2));
% I didn't need all 9 entries, since the 3x3 matrix is symmetric
F =[p1*p1;...
    p1*p2;...
    p1*p3;...
    p2*p2;...
    p2*p3;...
    p3*p3];

end

我希望,有人可以利用这些信息。