计算给出错误结果的线性 ODE 解的简单脚本

Simple script that computes a solution of linear ODEs giving wrong result

这是一个涉及编程和数学的问题。因此,我正在尝试编写一个代码来计算 . The mathematical formula it's shown above:

描述的线性 ODE 系统的通解

方程中出现的希腊符号\PHI是expm(A*t)

 clear all

 A=[-2]; %system matrix

 t0=1; %initial time of simulation

 tf=2; %final time of simulation

 syms t x_0 

 x0=x_0;

 hom=expm(A*t); %hom means "homogeneous solution"

 hom_initialcond=hom*x0;%this is the homogeneous solution multiplied by the initial conditon

 invhom=inv(hom); %this is the inverse of the greek letter at which, multiplied by the input of the system, composes the integrand of the integral

 g=5*cos(2*t); %system input

 integrand=invhom*g; %computation of the integrand

 integral=int(integrand,t0,t); %computation of the definite integral from t0 to t, as shown by the math formula

 partsol=hom*integral; %this is the particular solution

 gen_sol=partsol+hom_initialcond %this is the general solution

 x_0=1; %this is the initial condition

 t=linspace(t0,tf); %vector of time from t0 to tf

 y=double(subs(gen_sol)); %here I am evaluating my symbolic expression

 plot(t,y)

问题是我的 ODE 解图看起来不太好,如您所见:

解法是错误的,因为图中显示的曲线不是从初始值等于 1 开始的。但它的形状与 MATLAB ODE 求解器给出的图非常相似:

但是,如果我设置 t0=0,那么我的代码和 MATLAB 求解器给出的图完全相等。因此,我的代码对于 t0=0 没问题,但是对于任何其他值,我的代码都会出错。

基本矩阵的通解是

或更常被视为

但由于初始时间通常取为零,基本矩阵的逆矩阵通常被省略,因为它是零处线性常系数问题(即 expm(zeros(n)) == eye(n))和c向量相当于初始条件向量。

将符号声明附近的一些行换成这个

 syms t x_0 c_0
 hom             = expm(A*t)                ;
 invhom          = inv(hom)                 ;
 invhom_0        = subs(invhom,t,sym(t0))   ;
 c_0             = invhom_0 * x_0           ;
 hom_initialcond = hom    * c_0             ;

应该为 non-zero 初始时间提供正确的解决方案。