我在使用leastsq命令时遇到一条错误消息,指出“无效索引”

问题描述 投票:0回答:1

我希望使用提供的数据 y1、y2 对非线性微分方程组进行参数估计,以找到系统参数 p(1) 和 p(2)。之后,我的目标是将这些数据与这些微分方程的解相拟合。但是,在使用leastsq命令时,我遇到了一条错误消息,指出“索引无效”。是什么原因导致这个问题?

clear
// Define the system of nonlinear equations
function [dy1, dy2, dy3] = nonlinear_eqns(y1, y2, p)
    dy1 = -p(1)*y1*y2;
    dy2 = p(1)*y1*y2 - p(2)*y2;
    dy3 = p(2)*y2;
endfunction
// Define the data
y1 = [1 2 3]';
y2 = [3 4 5]';
y3 = [6 7 8]';
t = [1 2 3]'; // Assuming time points are 1, 2, 3

// Define the objective function for least squares
function e = objective(y1,y2,y3)
    //global y1 y2 y3 t;
    time = [1:1:3];
    y_model = ode(y1(1), y2(1), y3(1), time, nonlinear_eqns); // initial conditions
    e = [y1 - y_model(:,1); y2 - y_model(:,2); y3 - y_model(:,3)];
endfunction

// Perform parameter estimation using least squares
p0 = [1; 1]; // Initial guess for parameters
p_fit = leastsq(p0, objective);

// Output the fitted parameters
disp('Parameters:');
disp(p_fit);

scilab
1个回答
0
投票

您对ode()和leastsq()的使用不正确,ode状态是单个向量(请参阅https://help.scilab.org/docs/2024.0.0/en_US/ode.html)并且您不这样做不尊重leastsq api(请参阅https://help.scilab.org/docs/2024.0.0/en_US/ode.html)。这是脚本的固定版本:

clear
// Define the system of nonlinear equations
function dy = nonlinear_eqns(t,y, p)
    dy = [-p(1)*y(1)*y(2)
           p(1)*y(1)*y(2) - p(2)*y(2)
           p(2)*y(2)];
endfunction
// Define the data
y = [1 2 3
     3 4 5
     6 7 8];
t = [1 2 3]; // Assuming time points are 1, 2, 3

// Define the objective function for least squares
function e = objective(p)
    time = 1:1:3;
    y_model = ode(y(:,1), time(1), time, nonlinear_eqns); // initial conditions
    e = y-y_model;
    e = e(:);
endfunction

// Perform parameter estimation using least squares
p0 = [1; 1]; // Initial guess for parameters
[fopt,p_fit] = leastsq(iprint=2, objective, p0);

// Output the fitted parameters
disp('Parameters:');
disp(p_fit);

但是,如果您想进一步了解本主题(使用常解法拟合时态数据),我建议您查看当前 Scilab 2024.0.0 中 ODE 中的演示模拟/日晷/参数识别

© www.soinside.com 2019 - 2024. All rights reserved.