如何修复Scilab中的“子矩阵定义不正确”?

时间:2019-06-08 20:14:05

标签: optimization ode least-squares scilab

我正在尝试找到三个参数(a,b,c)以使用ODE求解器拟合我的实验数据,并使用Scilab内置函数按最小二乘法进行优化。 但是,我在行“ y_exp(:,1)= [0.135 ...”

上始终显示消息“子矩阵定义不正确”。

当我尝试其他一系列数据(t,yexp),例如原始模板中使用的数据时,我没有收到错误消息。在以下位置找到了我使用的模板:https://wiki.scilab.org/Non%20linear%20optimization%20for%20parameter%20fitting%20example

function dy = myModel ( t , y , a , b, c ) 
// The right-hand side of the Ordinary Differential Equation.
dy(1) = -a*y(1) - b*y(1)*y(2) 
dy(2) = a*y(1) - b*y(1)*y(2) - c*y(2)
endfunction 

function f = myDifferences ( k ) 
// Returns the difference between the simulated differential 
// equation and the experimental data.
global MYDATA
t = MYDATA.t
y_exp = MYDATA.y_exp
a = k(1) 
b = k(2) 
c = k(3)
y0 = y_exp(1,:)
t0 = 0
y_calc=ode(y0',t0,t,list(myModel,a,b,c)) 
diffmat = y_calc' - y_exp
// Make a column vector
f = diffmat(:)
MYDATA.funeval = MYDATA.funeval+ 1
endfunction 

// Experimental data 

t = [0,20,30,45,75,105,135,180,240]'; 
y_exp(:,1) = 
[0.135,0.0924,0.067,0.0527,0.0363,0.02445,0.01668,0.012,0.009]'; 
y_exp(:,2) = 
[0,0.00918,0.0132,0.01835,0.0261,0.03215,0.0366,0.0393,0.0401]'; 

// Store data for future use
global MYDATA;
MYDATA.t = t;
MYDATA.y_exp = y_exp;
MYDATA.funeval = 0;

function val = L_Squares ( k ) 
// Computes the sum of squares of the differences.
f = myDifferences ( k ) 
val = sum(f.^2)
endfunction 

// Initial guess
a = 0; 
b = 0; 
c = 0;
x0 = [a;b;c];  

[fopt ,xopt]=leastsq(myDifferences, x0)

有人知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

只需将28,29行改写为

y_exp = [0.135,0.0924,0.067,0.0527,0.0363,0.02445,0.01668,0.012,0.009 
         0,0.00918,0.0132,0.01835,0.0261,0.03215,0.0366,0.0393,0.0401]'; 

或在第1行插入clear(您之前可能已经定义y_exp,但大小不同)。