使用MATLAB查找方程中的常数值



我有方程F(f)=a*f^3+b*f+c。我有已知的数据向量,p,自变量,‘f’。我需要找到abc的值。我尝试过的:

function [ val ] = myfunc(par_fit,f,p)
    % This gives me a,b,c
    % p= af^3 +bf +c
    val = norm(p - (par_fit(1)*(f.^3))+ (par_fit(2)*f) + (par_fit(3)));
end
my_par = fminsearch(@(par_fit) myfunc(par_fit,f,p),rand(1,3));

这给了我my_par = [1.9808 -2.2170 -24.8039],或者a=1.9808b=-2.2170c=-24.8039,但我要求b应该大于5,c应该大于零。

我认为您的问题可能是因为您的目标函数不正确:

val = norm(p - (par_fit(1)*(f.^3))+ (par_fit(2)*f) + (par_fit(3)));

应该是:

val = norm(p-(par_fit(1)*f.^3+par_fit(2)*f+par_fit(3)));

但是,当使用fmincon而不是fminsearch进行最小化时,可以约束变量的值。通过将lb输入设置为[-Inf -Inf 0],允许前两个系数为任何实数,但第三个系数必须大于或等于零。例如:(我还展示了如何使用矩阵方法解决问题(没有非负性约束)

% Sample data
f=(0:.1:1).';
p=2*f.^3+3*f+1+randn(size(f))
% Create Van der Monde matrix
M=[f.^3 f f.^0];
C=Mp; % Solve the matrix problem in a least squares sense if size(f)>size(F)
my_par=fmincon(@(c) norm(p-(c(1)*f.^3+c(2)*f+c(3))),rand(1,3),[],[],[],[],[-Inf 5 0],[])
C.'
plot(f,p,'o',f,M*C,f,my_par(1)*f.^3+my_par(2)*f+my_par(3))

最新更新