我有多套x
和y
。其中一个如下:
x = [ 1.4 15.15 49.395 98.8 151.475 184.41 230.51 259.2 ]
y = [ 12.15 21.2125 25.15125 25.3 24.63125 28.8975 29.8725 35.2 ]
除此之外,我还有两个与k
相关的参数n
和x
,如下所示
q = k.* x^-n
我有三个功能:
e = q.*q - y.*y
f = q-y
g = (q-y)^1/2
首先,我想最小化与e
相关的函数y
,如下所示:
e = q.*q - y.*y
之后我想同时最小化函数f
,然后是g
。
答案 0 :(得分:1)
您的代码中存在一些缺陷。
这里有一些代码,技术上做的,你想要的。我还添加了函数h
,它最小化了平方误差之和,这是默认的最小化函数
%// Data
x = [ 1.4 15.15 49.395 98.8 151.475 184.41 230.51 259.2 ];
y = [ 12.15 21.2125 25.15125 25.3 24.63125 28.8975 29.8725 35.2 ];
%// create model function q with parameters p(1) = k and p(2) = n
q = @(p, x) p(1)*x.^(-p(2));
%// create the desired error-functions for minimization
e = @(p) sum((y.^2 - q(p, x)).^2); %// minimization function
f = @(p) sum(abs(y - q(p, x))); %// better sum over absolute values
g = @(p) sum(sqrt(abs(q(p, x) - y))); %// better take square roots of absolute values
h = @(p) sum((q(p, x) - y).^2); %// default minimizaton function
p0 = [1, -0.5]; % an initial guess
[p_fit_e, r_e] = fminsearch(e, p0) % Optimize
[p_fit_f, r_f] = fminsearch(f, p0) % Optimize
[p_fit_g, r_g] = fminsearch(g, p0) % Optimize
[p_fit_h, r_h] = fminsearch(h, p0) % Optimize
%// visualization
figure
plot(x,y,'ko')
hold on
X = linspace(min(x), max(x), 100);
plot(X, q(p_fit_e, X), 'r-')
plot(X, q(p_fit_f, X), 'g-')
plot(X, q(p_fit_g, X), 'b-')
plot(X, q(p_fit_h, X), 'k-')
您的优化错误 - 函数e
似乎失败了。
请注意,对于函数h
的默认情况,您也可以使用nlinfit
,如下所示:
p_fit_h_nlinfit = nlinfit(x, y, q, p0);
在这种情况下产生相同的结果:
p_fit_h_nlinfit =
12.3018 -0.1675
p_fit_h =
12.3018 -0.1675
答案 1 :(得分:0)
@Nras I have modified the syntax and thanks for your help
%//数据 x = [1.4 15.15 49.395 98.8 151.475 184.41 230.51 259.2]; y = [12.15 21.2125 25.15125 25.3 24.63125 28.8975 29.8725 35.2];
%//使用参数p(1)= k和p(2)= n创建模型函数q q = @(p,x)p(1)* x。^( - p(2));
%//为最小化创建所需的错误函数 e = @(p)sum((y。^ 2 - q(p,x))。^ 2); %//最小化函数 f = @(p)sum(abs(y-q(p,x))); %//更好地求和绝对值 g = @(p)sum(sqrt(abs(q(p,x)-y))); %//更好地取绝对值的平方根 h = @(p)sum((q(p,x)-y)。^ 2); %//默认最小化函数
p0 = [1, 0.5]; % an initial guess
A = [];
b=[];
Aeq = [];
beq=[];
lb = [-inf,0];
ub = [inf,1];
nonlcon= []
options = optimset('Display','iter','Algorithm','active-set');
options.MaxFunEvals = 100000;
options.MaxIter = 100000
[p_fit_e, r_e] = fmincon(e,p0,A,b,Aeq,beq,lb,ub,nonlcon,options) % Optimize
[p_fit_f, r_f] = fmincon(f, p0,A,b,Aeq,beq,lb,ub,nonlcon,options) % Optimize
[p_fit_g, r_g] = fmincon(g, p0,A,b,Aeq,beq,lb,ub,nonlcon,options) % Optimize
[p_fit_h, r_h] = fmincon(h,p0,A,b,Aeq,beq,lb,ub,nonlcon,options)% Optimize
[minVal minInd] = min(r_e)
[minVal minInd] = min(r_f)
[minVal minInd] = min(r_g)
[minVal minInd] = min(r_h)
e1 = p_fit_e(1)*x.^(-p_fit_e(2));
f1 = p_fit_f(1)*x.^(-p_fit_f(2));
g1 = p_fit_g(1)*x.^(-p_fit_g(2));
h1 = p_fit_h(1)*x.^(-p_fit_h(2));
figure(1)
plot(x,e1)
hold on
plot(x,y)
figure(2)
plot(x,f1)
hold on
plot(x,y)
figure(3)
plot(x,g1)
hold on
plot(x,y)
figure(4)
plot(x,h1)
hold on
plot(x,y)