【问题标题】:How do I fit a nonlinear function correctly in matlab如何在matlab中正确拟合非线性函数
【发布时间】:2018-11-18 20:17:55
【问题描述】:

我有下表,名为“test”:

    0.0037071        0.5 
     0.015203          1 
     0.035039        1.5 
     0.062272          2 
     0.093988        2.5 
      0.12776          3 
      0.16291        3.5 
      0.19991          4 
      0.24002        4.5 
      0.28574          5 
      0.34696        5.5 
      0.47879          6 
       1.8882     6.1125 

现在我想使用 matlab 拟合非线性函数:

modelfun = @(b,x)erf(b(1)*x)./b(2) + b(3);
beta0 = [0, 0, 0];
mdl = fitnlm(test,modelfun,beta0)

但我收到以下错误:

Error using nlinfit (line 247)
No usable observations after removing NaNs in Y and in the result of evaluating MODELFUN at the initial value BETA0.

我该如何解决这个问题? (以及如何获得用于绘图的最终拟合非线性函数?)

【问题讨论】:

    标签: matlab


    【解决方案1】:

    我不熟悉fitnlm,但是您可以使用优化工具箱中的另一个功能,例如lsqnonlin

    % splitting your data in vectors
    x = data(:,1);
    y = data(:,2);
    
    % the model you want to fit
    modelfun = @(b,x) erf(b(1)*x)./b(2) + b(3);
    
    % define a cost function, the error between the data to fit and the
    % prediction of the model
    cost_fun = @(b,x,y) modelfun(b,x) - y;
    
    % initial guess
    beta0 = [1 1 1];
    
    % perform optimization
    p = lsqnonlin(@(p) cost_fun(p,x,y), beta0);
    

    事实证明,您的模型返回的 beta0 全为零的 NaN 值。这就是您收到错误的原因。这是因为您最初除以 0,b(2) = 0。将您的beta0 更改为一个,即可解决问题,您可以使用fitnlm

    % splitting your data in vectors
    x = data(:,1);
    y = data(:,2);
    
    modelfun = @(b,x) erf(b(1)*x)./b(2) + b(3);
    
    % initial guess
    beta0 = [1 1 1];
    mdl = fitnlm(x,y,modelfun,beta0)
    

    要绘制数据,只需从mdl 中的表中提取参数并将它们存储在b_est(第一列)中,然后执行y_est = modelfun(b_est,x)。如果您使用lsqnonlin,它们将存储在输出变量p

    然后就画图:plot(t,y,t,y_est)

    【讨论】:

    • 你知道如何将拟合函数与数据一起绘制吗?
    • 非常感谢!它告诉我“参数数量错误”。我认为这是因为“测试”是一张桌子......
    • @james,哦,是的,没错,您应该将表格拆分为向量,就像我在答案顶部所做的那样
    猜你喜欢
    • 1970-01-01
    • 2014-03-28
    • 1970-01-01
    • 2021-02-25
    • 2017-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    相关资源
    最近更新 更多