如何在Matlab中使平方和高原条件相适应?

时间:2018-07-29 13:39:48

标签: matlab quadratic

x和y的值如下:

x=[0,80,100,120,150], 
y=[1865,3608,4057,4343,4389]

我的等式如下:

y=a(x)^2+b(x)+c, x < xc(Ymax) ....(1)

y=yp, x >= xc(Ymax) ....(2)

我想拟合这两个方程,其中第一个方程将提供二次拟合,而第二个方程将提供线性拟合。问题是,当我们尝试拟合时,它以二次形式(eq.1)为我们提供了最佳拟合,而没有包括线性拟合(eq.2)。

我们还提供了已使用的MATLAB代码:

yf = @(b,x) b(1).*x.^2+b(2)*x+b(3);
B0 = [0.006; 21; 1878];
[Bm,normresm] = fminsearch(@(b) norm(y - yf(b,x)), B0);
a=Bm(1);
b=Bm(2);
c=Bm(3);
xc=-b/(2*a);
p=c-(b^2/(4*a));
 if (x < xc) 
      yfit = a.*x.^2+ b*x+c;
 else yfit = p;
 end
plot(x,yfit)
hold on 
plot(x,y,'*')
hold off

我们正在提供从结果中获得的图形(fig(1))。为了进一步理解,我们还证明了一个图(fig(2)),该图显示了结果应该如何得出。

1 个答案:

答案 0 :(得分:1)

我修改了输入数据,因此您可以看到结果:

%input data
x = [0;     20;     50;     80;     100;    120;    150;    160;    180;    200;    220;     240]; 
y = [1865;  2500;  3000;   3608;   4057;   4343;   4389;    4250;   4300;   4280;   4350;    4200];

%find the index of the maximum y value
[~, idx] = max(y);

%initial parameter values
a0 = -1;
b0 = 1;
c0 = 2;

p0 = [a0 b0 c0];

%optimization options
options = optimset('Display','iter');

%optimization call
p = fminsearch(@fun_so_180730, p0, options, x, y, idx);

%plot of the fitted function based on two parts (quadratic and linear)
x_fit_1 = (0:2:x(idx))'; 
x_fit_2 = (x(idx):2:max(x))';

y_fit_1 = p(1)*x_fit_1.^2 + p(2)*x_fit_1 + p(3);
y_fit_2 = ones(size(x_fit_2))*y_fit_1(end);

figure;
plot(x, y, 'bo');
hold on;
plot([x_fit_1; x_fit_2], [y_fit_1; y_fit_2], 'r-');
hold off;
grid on;

优化功能作为单独的文件:

function [f] = fun_so_180730(p, x, y, idx)

    a = p(1);
    b = p(2);
    c = p(3);

    % calculation of the current function
    y_prime = zeros(size(y));

    %quadratic part
    y_prime(1:idx) = a*x(1:idx).^2 + b*x(1:idx) + c;

    %linear part if there are elements after the maximum y value
    if (idx < numel(y))
        y_prime(idx+1:end) = y_prime(idx);
    end

    % current cost as a vector norm
    f = norm(y - y_prime);
end

结果:

piecewise curve fitting using the fminsearch optimizer