matlab中_ODE45的用法_英文资料
ode45求解微分方程加入齿侧间隙函数的matlab程序_解释说明
ode45求解微分方程加入齿侧间隙函数的matlab程序解释说明1. 引言1.1 概述在科学和工程领域中,微分方程广泛应用于描述动态系统的行为。
针对复杂的微分方程,求解它们的解析解往往十分困难甚至不可行。
因此,数值求解方法成为研究者们探索问题背后物理现象的重要手段。
本文将重点介绍一种常用且高效的数值方法——ode45(一种ode系列函数),并结合齿侧间隙函数的应用来解决微分方程。
我们将使用MATLAB作为编程工具,并通过设计相应程序来进行仿真实验。
1.2 文章结构本篇文章总共包括五个部分:引言、ode45求解微分方程加入齿侧间隙函数的MATLAB程序、实验结果与讨论、结论以及结束语。
接下来,在引言部分中,我们将简要介绍文章的主题和内容,并概述每个章节所涉及到的问题。
1.3 目的本文旨在深入探讨如何使用ode45函数求解微分方程,并结合齿侧间隙函数进行更准确地建模和仿真。
通过详细说明MATLAB程序设计方法和实验结果与讨论,我们希望能够全面了解齿侧间隙函数在微分方程求解中的应用,并提供一种有效而可靠的数值方法。
最后,我们将总结ode45求解微分方程加入齿侧间隙函数的MATLAB程序的优势和限制,并对未来的研究和应用进行展望。
以上是“1. 引言”部分所包含的内容。
该部分主要介绍了本文的概述、结构和目的。
接下来,我们会详细展开介绍“2. ode45求解微分方程加入齿侧间隙函数的MATLAB程序”的相关内容。
2. ode45求解微分方程加入齿侧间隙函数的matlab程序2.1 ode45求解微分方程的介绍ode45是MATLAB中用于数值求解常微分方程(ODE)的函数之一。
它利用了Runge-Kutta法进行数值积分,具有较高的精度和适应性。
ode45可以处理非刚性和刚性系统,并且能够自动调整步长以确保结果的准确性。
2.2 齿侧间隙函数在微分方程中的应用齿侧间隙函数是一种描述啮合噪声产生机制的函数,常用于模拟和研究啮合传动系统中的振动和噪声特性。
ode45函数用法
ode45函数用法ode45函数是MATLAB中的一个常用函数,用于求解常微分方程初值问题。
它实质上是利用了4阶和5阶Runge-Kutta方法的一种变种形式,可以对一阶和高阶常微分方程进行数值求解。
ode45函数的主要语法格式为:[t, y] = ode45(@fun, tspan, y0)其中,@fun是一个函数句柄,用于定义微分方程dy/dt=f(t,y)的右侧函数f(t,y)。
tspan是求解的时间范围,通常为一个二元向量[tstart, tend]。
y0是微分方程的初始条件。
当调用ode45函数时,它会返回两个向量t和y,其中t是时间向量,y是对应时间点的解向量。
可以通过绘图或其他后续处理分析这些解。
ode45函数的使用方法具有一定的灵活性。
首先,可以通过在函数f(t,y)中定义额外的参数来解决一些特定问题。
例如,可以将常数或其他变量作为输入参数传递给f函数。
其次,可以在tspan中指定更复杂的时间范围。
除了指定[tstart, tend]之外,还可以指定等间隔的时间点或自定义时间点。
这样可以对非等间隔的时间步长进行模拟。
另外,ode45函数还可以通过指定其他选项来进行更精确的求解或控制数值计算。
例如,可以通过指定'AbsTol'和'RelTol'选项来调整计算的绝对误差和相对误差。
还可以通过指定'Events'选项来检测事件,并在事件发生时中断求解。
除了以上基本用法外,ode45函数还可以与其他函数和工具箱进行配合使用。
例如,可以使用odeplot函数在求解过程中实时绘制解曲线。
还可以使用odephas2函数对微分方程的相平面进行绘制。
总之,ode45函数是MATLAB中一个强大的求解常微分方程的工具,它不仅具有灵活的使用方法,而且可以与其他函数和工具箱进行配合使用。
熟练掌握ode45函数的用法对于数学建模和科学计算等应用非常有价值。
matlab中ode45函数的用法
matlab中ode45函数的用法matlab是一款非常流行的数学软件,它能够帮助用户解决各种复杂的数学问题。
其中,matlab中的ode45函数是一种用于求解常微分方程的函数,它能够有效地计算常微分方程的解。
本文将介绍ode45函数的使用方法,以帮助用户掌握使用matlab求解常微分方程的基础知识。
一、ode45函数介绍ode45函数是matlab中解决微分方程的函数,它是matlab中用于求解常微分方程的标准函数。
该函数的计算方法基于Runge-Kutta 的四五次算法,采用分步法来解决常微分方程,能够求出精度比较高的解,是求常微分方程的首选函数。
ode45函数的使用方法如下:1.首先,用户需要输入一个初值条件,以确定微分方程的初始状态。
2.接着,需要编写一个函数,来表示被计算的常微分方程。
3.然后,在matlab命令行中输入[t,y]=ode45(func[t0,tf],y0),其中“func”表示前面编写的函数,[t0,tf]表示计算时间范围,y0表示初值条件。
4.最后,会得到一组时间t和变量y的值,它们可以用matlab 的plot函数来绘制出微分方程的解。
二、ode45函数的实例下面将通过一个实例来演示ode45函数的使用。
比如,要求解$ frac{dy}{dt}=y $,初值条件:y(0)=1。
首先,把微分方程写成函数形式:func=@(t,y)y接着,输入命令:[t,y]=ode45(func[0 5],1)最后,用matlab的plot函数绘图:plot(t,y)此时,就可以得到一条曲线,曲线上点分别对应函数的解,即可完成常微分方程的求解。
三、总结本文介绍了matlab中ode45函数的使用方法,ode45函数是matlab中求解常微分方程的标准函数,它基于Runge-Kutta的四五次算法,能够有效地计算常微分方程的解,以帮助用户更好地掌握matlab求解微分方程的基础知识。
ODE45函数的使用——翻译
在Matlab 中使用ode45简介Matlab 中常微分方程常用的函数是ODE45,这个函数能够利用--龙哥库塔法--有效求解带时间变量步长的计算。
Ode45用于求解如下的一般问题:)(()00,,x t x x t f dtdx ==(1) 其中,时间t 是独立变量,x 为时间相关矢量,)(x t f ,是时间t 和x 的函数。
当(1)右边的)(x t f ,是固定的,且给定x 的初始值,那么问题的解是唯一的。
在ME175中,解法是不完整的,但是只要你解决了问题,就可以获得ODE 代表的系统运动趋势。
这有利于得到一个直观的印象,看起来很复杂的常微分方程,代表的质点运动轨迹确实简单明了的。
以下简要解释如何得到运动轨迹:第一步:对给定的ODE 方程进行降阶处理,得到一系列一阶方程这就是你要做的第一步,在一张草稿纸上处理。
例如,给定ODE 方程如下:1,3,5002-===-+⋅⋅⋅⋅y y y e y y m y (2)对本问题,矢量x 有两个组成分量:y 和⋅y ,或 ()()⋅==yx yx 21(3)且 ()()()()()()()()()()()211251221x e x m dt x d x dt x d x +-==(4) 其中,用(3)中的式子代表了y ,⋅y ,⋅⋅y ,于是把(2)改写为(4)。
如果求解的问题有更多阶数更多变量呢?例如,我们除了有上面的方程(2),同时还有以下的方程:().1,0,sin 002233===-+⋅z z t z dt z d dt z d (5) 那么,我们可以通过构造更大的矢量x 同时求解y ,z :()()()⋅⋅⋅===z x z x zx 543 (6)然后⎥⎦⎤⎢⎣⎡=⋅⋅⋅⋅z z z y y x ,,,, (7) 以及 [⎥⎦⎤==⋅⋅=⋅==⋅==000000,,,,t t t t t t z z z y y x (8) 其中,y 变量和z 变量的放置位置对求解不造成影响。
ode45函数用法
ode45函数用法MATLAB中的ode45函数是一种用来求解常微分方程的函数,其精准性和容错性使其成为了微分方程求解过程中常用的一种方法。
该函数的最大优点是其精确度高、适用范围广,可处理几乎所有的常微分方程。
本文将介绍ode45函数的使用方法,包括函数的调用方法、输入参数的含义、输出结果的解释等。
ode45函数的调用方法是:[t,y] = ode45(odefun,tspan,y0,options)其中的含义是:- t:是一个列向量,表示求解的时刻点。
- y:是一个列向量,表示对应的解向量。
- odefun:是一个函数句柄,表示需要求解的常微分方程。
- tspan:是一个行向量,表示求解的时间区间。
- y0:是一个向量,表示初始状态。
- options:是一个结构体,表示求解时的选项。
根据输入参数,ode45函数的相关参考内容如下:1. odefunodefun为半隐式的Runge-Kutta预测校正算法函数,用于预测下一步的y值,并校正预测误差。
输入参数表示对时间和当前的y向量的双参数函数,如dydt = odefun(t, y)。
dydt表示y的一阶导数,t表示时间,y表示状态向量。
odefun函数需要返回dydt。
2. tspantspan是一个由两个数值组成的向量,表示求解常微分方程的时间区间,格式为tspan = [t0 tf]。
t0表示初值的时间,tf表示求解的时间终点。
tspan可以是一行或一列向量,其元素不必等间距。
3. y0y0是一个列向量,表示初始状态值,这个初始状态值为t0时刻的y值。
4. optionsoptions是一个结构体,表示求解常微分方程时的选项。
options结构体有多个参数,常用字段有以下几种:- AbsTol:表示绝对误差容许值,可以是标量或列向量,是一个数值或向量。
默认值是1e-6,越小越精确。
- RelTol:表示相对误差容许值,可以是标量或列向量,是一个数值或向量。
matlab ode45用法
matlab ode45用法MATLAB中的ode45函数是一个常用的求解常微分方程数值方法的函数。
它的基本用法是解决给定的常微分方程组,其中方程是一个或多个未知函数以及它们的导数的函数关系。
ode45函数的完整语法如下所示:[t,y] = ode45(odefun,tspan,y0,options)其中,odefun是指定的常微分方程的函数句柄,tspan是求解的时间范围,y0是初始条件,而options是一个可选参数列表用于设置算法和求解的精度。
对于该问题,我们将以odefun函数的编写开始解释ode45的用法。
ode45方法中的odefun函数是用户自定义的函数,它返回一个欲求解函数f的导数值。
例如,考虑以下常微分方程:dy/dt = f(t,y)其中y是待求的函数,t是自变量,f(t,y)是给定的函数关系。
我们需要将这个常微分方程表示为一个函数文件,并命名为odefun。
在MATLAB的编辑器中,我们可以创建一个名为odefun.m的文件,并将以下代码添加到文件中:matlabfunction dydt = odefun(t,y)dydt = 2 * t; 使用示例,实际应根据具体问题编写end在这个例子中,我们假设f(t,y) = 2t,因此派生函数是2t。
现在让我们使用ode45函数来解决常微分方程。
我们将定义时间间隔,并提供初始条件:matlabtspan = [0 10]; 定义时间间隔y0 = 0; 定义初始条件现在我们可以调用ode45函数并传递定义的参数:matlab[t, y] = ode45(@odefun, tspan, y0);通过调用ode45函数,我们获得了两个输出参数t和y。
t是时间向量,y 是对应时间点上函数的值。
最后,我们可以使用plot函数将结果可视化:matlabplot(t, y);xlabel('t');ylabel('y');title('Solution of dy/dt = 2t');以上就是使用ode45函数求解常微分方程的基本步骤。
Matlab中解常微分方程的ode45
Matlab 中解常微分方程的ode45ode 是专门用于解微分方程的功能函数,他有ode23,ode45,ode23s等等,采用的是Runge-Kutta 算法。
ode45 表示采用四阶,五阶runge-kutta单步算法,截断误差为(△x)A3。
解决的是Nonstiff(非刚性)的常微分方程•是解决数值解问题的首选方法,若长时间没结果,应该就是刚性的,换用ode23 来解.其他几个也是类似的用法使用方法[T,Y] = ode45(odefun,tspan,y0)odefun 是函数句柄,可以是函数文件名,匿名函数句柄或内联函数名tspan 是区间[t0 tf] 或者一系列散点[t0,t1,...,tf]y0 是初始值向量T 返回列向量的时间点Y 返回对应T 的求解列向量[T,Y] = ode45(odefun,tspan,y0,options)options是求解参数设置,可以用odeset在计算前设定误差,输出参数,事件等[T,Y,TE,YE,IE] =ode45(odefun,tspan,y0,options)每组(t,Y)之产生称为事件函数。
每次均会检查是否函数等于零。
并决定是否在零时终止运算。
这可以在函数中之特性上设定。
例如以events或@events产生一函数。
[value,isterminal,direction]=events(t,y) 其中,value(i) 为函数之值,isterminal(i)=1 时运算在等于零时停止,=0 时继续;direction(i)=0 时所有零时均需计算(默认值) ,+1 在事件函数增加时等于零,-1 在事件函数减少时等于零等状况。
此外,TE, YE, IE 则分别为事件发生之时间,事件发生时之答案及事件函数消失时之指针i。
sol =ode45(odefun,[t0 tf],y0...) sol 结构体输出结果应用举例1 求解一阶常微分方程程序:odefun=@(t,y) (y+3*t)/t A2; % 定义函数tspan=[1 4]; % 求解区间y0=-2; % 初值[t,y]=ode45(odefun,tspan,y0);plot(t,y) %作图title('tA2y''=y+3t,y(1)=-2,1<t<4') legend('tA2y''=y+3t') xlabel('t') ylabel('y') % 精确解% dsolve('tA2*Dy=y+3*t','y(1)=-2') % ans = % (3*Ei(1) - 2*exp(1))/exp(1/t) - (3*Ei(1/t))/exp(1/t)2 求解高阶常微分方程关键是将高阶转为一阶,odefun 的书写.F(y,y',y''...y(n-1),t)=0 用变量替换,y1=y,y2=y'... 注意odefun 方程定义为列向量dxdy=[y(1),y(2) ]程序: function Testode45 tspan=[3.9 4.0]; % 求解区间y0=[2 8]; % 初值[t,x]=ode45(@odefun,tspan,y0); plot(t,x(:,1),'-o',t,x(:,2),'-*') legend('y1','y2')title('y” ”=-t*y + e A t*y" +3sin2t') xlabel('t') ylabel('y') function y=odefun(t,x) y=zeros(2,1); % 列向量y(1)=x(2);y(2)=-t*x(1)+exp(t)*x(2)+3*sin(2*t);end end。
ode45 matlab 例子
ode45 matlab 例子ode45 MATLAB 例子1. 简介ode45 是 MATLAB 中一个常用的求解常微分方程(ODE)的函数。
它使用了一个基于 Runge-Kutta 方法的算法来解决ODE问题。
2. 线性ODE的例子下面我们通过一个线性ODE的例子来说明 ode45 的基本用法。
线性ODE的定义:假设有一个一阶线性ODE,形式如下:dy/dt = a*y + b其中 a 和 b 是常数,y 是未知函数。
例子:考虑一个简单的线性ODE:dy/dt = 2*t*y + t^2为了使用 ode45 解决这个问题,我们需要定义一个 MATLAB 函数来表示这个方程:function dydt = myODE(t, y)dydt = 2*t*y + t^2;end然后,我们可以使用 ode45 来求解该问题:[t, y] = ode45(@myODE, [0 1], 1);上述代码中: - @myODE表示将myODE函数作为变量传递给ode45 函数。
- [0 1]表示求解的时间区间是 [0, 1]。
- 1表示初始条件。
3. 非线性ODE的例子除了线性ODE,ode45 也可以求解非线性ODE。
下面我们通过一个非线性ODE的例子来说明。
非线性ODE的定义:假设有一个二阶非线性ODE,形式如下:d^2y/dt^2 + a*dy/dt + b*y + c*y^2 = 0其中 a、b 和 c 是常数,y 是未知函数。
例子:考虑一个简单的非线性ODE:d^2y/dt^2 + 2*dy/dt + 3*y + 4*y^2 = 0为了使用 ode45 解决这个问题,我们需要将这个二阶ODE转化为两个一阶ODE。
令 z = dy/dt,我们可以得到以下一阶ODE系统:dz/dt = -2*z - 3*y - 4*y^2dy/dt = zfunction dydt = myODE(t, y)dydt = zeros(2,1);dydt(1) = -2*y(2) - 3*y(1) - 4*y(1)^2;dydt(2) = y(1);end然后,我们可以使用 ode45 来求解该问题:[t, y] = ode45(@myODE, [0 1], [1 0]);上述代码中,初始条件是[1 0],因为我们需要同时指定 y 和z 的初始值。
matlab中ode45函数编写
functi on vararg out = ode45(ode,tspan,y0,option s,vararg in)%ODE45 Solvenon-stiffdiffer entia l equati ons, medium ordermethod.% [TOUT,YOUT] = O DE45(ODEFUN,TSPAN,Y0) with TSPAN= [T0 TFINAL] integr ates% the system of differ entia l equati ons y' = f(t,y) from time T0 to TFINAL % with initia l condit ionsY0. ODEFUN is a functi on handle. For a scalarT% and a vector Y, ODEFUN(T,Y) must return a column vector corres pondi ng % to f(t,y). Each row in the soluti on arrayYOUT corres ponds to a time % return ed in the column vector TOUT. To obtain soluti ons at specif ic % timesT0,T1,...,TFINAL (all increa singor all decrea sing), use TSPAN=% [T0 T1 ... TFINAL].%% [TOUT,YOUT] = ODE45(ODEFUN,TSPAN,Y0,OPTION S) solves as abovewith defaul t% integr ation proper tiesreplac ed by values in OPTION S, an argume nt create d % with the ODESET functi on. See ODESET for detail s. Common ly used option s % are scalar relati ve errortolera nce 'RelTol' (1e-3 by defaul t) and vector % of absolu te errortolera nces'AbsTol' (all compon ents1e-6 by defaul t). % If certai n compon entsof the soluti on must be non-negati ve, use% ODESET to set the 'NonNeg ative' proper ty to the indice s of these% compon ents.%% ODE45can solveproble ms M(t,y)*y' = f(t,y) with mass matrix M that is % nonsin gular. Use ODESET to set the 'Mass' proper ty to a functi on handle % MASS if MASS(T,Y) return s the valueof the mass matrix. If the mass matrix % is consta nt, the matrix can be used as the valueof the 'Mass' option. If% the mass matrix does not depend on the statevariab le Y and the functi on % MASS is to be called with one inputargume nt T, set 'MState Depen dence' to% 'none'. ODE15S and ODE23T can solveproble ms with singul ar mass matric es. %% [TOUT,YOUT,TE,YE,IE] = ODE45(ODEFUN,TSPAN,Y0,OPTION S) with the'Events'% proper ty in OPTION S set to a functi on handle EVENTS, solves as above% whilealso findin g wherefuncti ons of (T,Y), called eventfuncti ons, % are zero. For each functi on you specif y whethe r the integr ation is% to termin ate at a zero and whethe r the direct ion of the zero crossi ng % matter s. Theseare the threecolumn vector s return ed by EVENTS:% [VALUE,ISTERM INAL,DIRECT ION] = EVENTS(T,Y). For the I-th eventfuncti on: % VALUE(I) is the valueof the functi on, ISTERM INAL(I)=1 if the integr ation % is to termin ate at a zero of this eventfuncti on and 0 otherw ise.% DIRECT ION(I)=0 if all zerosare to be comput ed (the defaul t), +1 if only % zeroswherethe eventfuncti on is increa sing,and -1 if only zeroswhere% the eventfuncti on is decrea sing.Output TE is a column vector of times% at whichevents occur. Rows of YE are the corres pondi ng soluti ons, and % indice s in vector IE specif y whicheventoccurr ed.%% SOL = ODE45(ODEFUN,[T0 TFINAL],Y0...) return s a struct ure that can be% used with DEVALto evalua te the soluti on or its firstderiva tiveat % any pointbetwee n T0 and TFINAL. The stepschosen by ODE45are return ed % in a row vector SOL.x. For each I, the column SOL.y(:,I) contai nsr % the soluti on at SOL.x(I). If events were detect ed, SOL.xe is a row vecto % of points at whichevents occurr ed. Column s of SOL.ye are thecorres pondi ng% soluti ons, and indice s in vector SOL.ie specif y whicheventoccurr ed.% Exampl e% [t,y]=ode45(@vdp1,[0 20],[2 0]);% plot(t,y(:,1));% solves the system y' = vdp1(t,y), usingthe defaul t relati ve error% tolera nce 1e-3 and the defaul t absolu te tolera nce of 1e-6 for each % compon ent, and plotsthe firstcompon ent of the soluti on.%% Classsuppor t for inputs TSPAN, Y0, and the result of ODEFUN(T,Y):% float: double, single%% See also% otherODE solver s: ODE23,ODE113, ODE15S, ODE23S, ODE23T, ODE23T B % implic it ODEs: ODE15I% option s handli ng: ODESET, ODEGET% output functi ons: ODEPLO T, ODEPHA S2, ODEPHA S3, ODEPRI NT% evalua tingsoluti on: DEVAL% ODE exampl es: RIGIDO DE, BALLOD E, ORBITO DE% functi on handle s: FUNCTI ON_HA NDLE%% NOTE:% The interp retat ion of the firstinputargume nt of the ODE solver s and % some proper tiesavaila ble throug h ODESET have change d in MATLAB6.0. % Althou gh we stillsuppor t the v5 syntax, any new functi onali ty is % availa ble only with the new syntax. To see the v5 help, type in% the comman d line% more on, type ode45, more off% NOTE:% This portio n descri bes the v5 syntax of ODE45.%% [T,Y] = ODE45('F',TSPAN,Y0) with TSPAN= [T0 TFINAL] integr atesthe% system of differ entia l equati ons y' = F(t,y) from time T0 to TFINAL with % initia l condit ionsY0. 'F' is a string contai ningthe name of an ODE % file. Functi on F(T,Y) must return a column vector. Each row in% soluti on arrayY corres ponds to a time return ed in column vector T. To % obtain soluti ons at specif ic timesT0, T1, ..., TFINAL (all increa sing% or all decrea sing), use TSPAN= [T0 T1 ... TFINAL].%% [T,Y] = ODE45('F',TSPAN,Y0,OPTION S) solves as abovewith defaul t% integr ation parame tersreplac ed by values in OPTION S, an argume nt% create d with the ODESET functi on. See ODESET for detail s. Common ly % used option s are scalar relati ve errortolera nce 'RelTol' (1e-3 by% defaul t) and vector of absolu te errortolera nces'AbsTol' (all% compon ents1e-6 by defaul t).%% [T,Y] = ODE45('F',TSPAN,Y0,OPTION S,P1,P2,...) passes the additi onal% parame tersP1,P2,... to the ODE file as F(T,Y,FLAG,P1,P2,...) (see% ODEFIL E). Use OPTION S = [] as a placeholder if no option s are set. %% It is possib le to specif y TSPAN, Y0 and OPTION S in the ODE file (see % ODEFIL E). If TSPANor Y0 is empty, then ODE45callsthe ODE file% [TSPAN,Y0,OPTION S] = F([],[],'init') to obtain any values not suppli ed % in the ODE45argume nt list. Emptyargume nts at the end of the call list % may be omitte d, e.g. ODE45('F').%% ODE45can solveproble ms M(t,y)*y' = F(t,y) with a mass matrix M that% nonsin gular. Use ODESET to set Mass to 'M', 'M(t)', or 'M(t,y)' if the % ODE file is codedso that F(T,Y,'mass') return s a consta nt,% time-depend ent, or time- and state-depend ent mass matrix, respec tivel y. % The defaul t valueof Mass is 'none'. ODE15S and ODE23T can solveproble ms % with singul ar mass matric es.%% [T,Y,TE,YE,IE] = ODE45('F',TSPAN,Y0,OPTION S) with the Events proper ty in% OPTION S set to 'on', solves as abovewhilealso locati ng zero crossi ngs % of an eventfuncti on define d in the ODE file. The ODE file must be% codedso that F(T,Y,'events') return s approp riate inform ation. See% ODEFIL E for detail s. Output TE is a column vector of timesat which% events occur, rows of YE are the corres pondi ng soluti ons, and indice s in% vector IE specif y whicheventoccurr ed.%% See also ODEFIL E% ODE45is an implem entat ion of the explic it Runge-Kutta(4,5) pair of % Dorman d and Prince called variou sly RK5(4)7FM, DOPRI5, DP(4,5) and DP54. % It uses a "free" interp olant of order4 commun icate d privat ely by% Dorman d and Prince. Localextrap olati on is done.% Detail s are to be foundin The MATLAB ODE Suite, L. F. Shampi ne and% M. W. Reiche lt, SIAM Journa l on Scient ificComput ing, 18-1, 1997.% Mark W. Reiche lt and Lawren ce F. Shampi ne, 6-14-94% Copyri ght 1984-2009 The MathWo rks, Inc.% $Revisi on: 5.74.4.10 $ $Date: 2009/04/21 03:24:15 $solver_name = 'ode45';% Checkinputsif nargin < 4option s = [];if nargin < 3y0 = [];if nargin < 2tspan= [];if nargin < 1error('MATLAB:ode45:NotEno ughIn puts',...'Not enough inputargume nts. See ODE45.');endendendend% Statsnsteps = 0;nfaile d = 0;nfeval s = 0;% OutputFcnHan dlesU sed = isa(ode,'functi on_ha ndle');output_sol= (FcnHan dlesU sed && (nargou t==1)); % sol = odeXX(...) output_ty = (~output_sol&& (nargou t > 0)); % [t,y,...] = odeXX(...)% Theremightbe no output reques ted...sol = []; f3d = [];if output_solsol.solver = solver_name;sol.extdat a.odefun = ode;sol.extdat a.option s = option s;sol.extdat a.vararg in = vararg in;end% Handle solver argume nts[neq, tspan, ntspan, next, t0, tfinal, tdir, y0, f0, odeArg s, odeFcn, ... option s, thresh old, rtol, normco ntrol, normy,hmax, htry, htspan, dataTy pe] = ...odearg ument s(FcnHan dlesU sed, solver_name, ode, tspan, y0, option s, vararg in);nfeval s = nfeval s + 1;% Handle the outputif nargou t > 0output Fcn = odeget(option s,'Output Fcn',[],'fast');elseoutput Fcn = odeget(option s,'Output Fcn',@odeplo t,'fast');endoutput Args= {};if isempt y(output Fcn)haveOu tputF cn = false;elsehaveOu tputF cn = true;output s = odeget(option s,'Output Sel',1:neq,'fast');if isa(output Fcn,'functi on_ha ndle')% With MATLAB 6 syntax pass additi onalinputargume nts to output Fcn. output Args= vararg in;endendrefine = max(1,odeget(option s,'Refine',4,'fast'));if ntspan > 2output At = 'Reques tedPo ints'; % output only at tspanpointselseif refine <= 1output At = 'Solver Steps'; % comput ed points, no refine mentelseoutput At = 'Refine dStep s'; % comput ed points, with refine ment S = (1:refine-1) / refine;endprints tats= strcmp(odeget(option s,'Stats','off','fast'),'on');% Handle the eventfuncti on[haveEv entFc n,eventF cn,eventA rgs,valt,teout,yeout,ieout] = ...odeeve nts(FcnHan dlesU sed,odeFcn,t0,y0,option s,vararg in);% Handle the mass matrix[Mtype, M, Mfun] =odemas s(FcnHan dlesU sed,odeFcn,t0,y0,option s,vararg in);if Mtype> 0 % non-trivia l mass matrixMsingu lar = odeget(option s,'MassSi ngula r','no','fast');if strcmp(Msingu lar,'maybe')warnin g('MATLAB:ode45:MassSi ngula rAssu medNo',['ODE45assume s '...'MassSi ngula r is ''no''. See ODE15S or ODE23T.']);elseif strcmp(Msingu lar,'yes')error('MATLAB:ode45:MassSi ngula rYes',...['MassSi ngula r cannot be ''yes'' for this solver. See ODE15S'...' or ODE23T.']);end% Incorp orate the mass matrix into odeFcn and odeArg s.[odeFcn,odeArg s] =odemas sexpl icit(FcnHan dlesU sed,Mtype,odeFcn,odeArg s,Mfun,M);f0 = feval(odeFcn,t0,y0,odeArg s{:});nfeval s = nfeval s + 1;end% Non-negati ve soluti on compon entsidxNon Negat ive = odeget(option s,'NonNeg ative',[],'fast');nonNeg ative = ~isempt y(idxNon Negat ive);if nonNeg ative% modify the deriva tivefuncti on[odeFcn,thresh oldNo nNega tive] =odenon negat ive(odeFcn,y0,thresh old,idxNon Negat ive);f0 = feval(odeFcn,t0,y0,odeArg s{:});nfeval s = nfeval s + 1;endt = t0;y = y0;% Alloca te memory if we're genera tingoutput.nout = 0;tout = []; yout = [];if nargou t > 0if output_solchunk= min(max(100,50*refine), refine+floor((2^11)/neq));tout = zeros(1,chunk,dataTy pe);yout = zeros(neq,chunk,dataTy pe);f3d = zeros(neq,7,chunk,dataTy pe);elseif ntspan > 2 % output only at tspanpointstout = zeros(1,ntspan,dataTy pe);yout = zeros(neq,ntspan,dataTy pe);else% allocin chunkschunk= min(max(100,50*refine), refine+floor((2^13)/neq));tout = zeros(1,chunk,dataTy pe);yout = zeros(neq,chunk,dataTy pe);endendnout = 1;tout(nout) = t;yout(:,nout) = y;end% Initia lizemethod parame ters.pow = 1/5;A = [1/5, 3/10, 4/5, 8/9, 1, 1];B = [1/5 3/40 44/45 19372/6561 9017/3168 35/3840 9/40 -56/15 -25360/2187 -355/33 00 0 32/9 64448/6561 46732/5247 500/1113 0 0 0 -212/729 49/176 125/1920 0 0 0 -5103/18656 -2187/67840 0 0 0 0 11/840 0 0 0 0 0];E = [71/57600; 0; -71/16695; 71/1920; -17253/339200; 22/525; -1/40];f = zeros(neq,7,dataTy pe);hmin = 16*eps(t);if isempt y(htry)% Comput e an initia l step size h usingy'(t).absh = min(hmax, htspan);if normco ntrolrh = (norm(f0) / max(normy,thresh old)) / (0.8 * rtol^pow);elserh = norm(f0 ./ max(abs(y),thresh old),inf) / (0.8 * rtol^pow);endif absh * rh > 1absh = 1 / rh;endabsh = max(absh, hmin);elseabsh = min(hmax, max(hmin, htry));endf(:,1) = f0;% Initia lizethe output functi on.if haveOu tputF cnfeval(output Fcn,[t tfinal],y(output s),'init',output Args{:});end% THE MAIN LOOPdone = false;while~done% By defaul t, hmin is a smallnumber such that t+hmin is only slight ly % differ ent than t. It mightbe 0 if t is 0.hmin = 16*eps(t);absh = min(hmax, max(hmin, absh)); % couldn't limitabsh untilnew hmin h = tdir * absh;% Stretc h the step if within 10% of tfinal-t.if 1.1*absh >= abs(tfinal - t)h = tfinal - t;absh = abs(h);done = true;end% LOOP FOR ADVANC ING ONE STEP.nofail ed = true; % no failed attemp tswhiletruehA = h * A;hB = h * B;f(:,2) = feval(odeFcn,t+hA(1),y+f*hB(:,1),odeArg s{:});f(:,3) = feval(odeFcn,t+hA(2),y+f*hB(:,2),odeArg s{:});f(:,4) = feval(odeFcn,t+hA(3),y+f*hB(:,3),odeArg s{:});f(:,5) = feval(odeFcn,t+hA(4),y+f*hB(:,4),odeArg s{:});f(:,6) = feval(odeFcn,t+hA(5),y+f*hB(:,5),odeArg s{:});tnew = t + hA(6);if donetnew = tfinal; % Hit end pointexactl y.endh = tnew - t; % Purify h.ynew = y + f*hB(:,6);f(:,7) = feval(odeFcn,tnew,ynew,odeArg s{:});nfeval s = nfeval s + 6;% Estima te the error.NNreje ctSte p = false;if normco ntrolnormyn ew = norm(ynew);errwt= max(max(normy,normyn ew),thresh old);err = absh * (norm(f * E) / errwt);if nonNeg ative && (err <= rtol) && any(ynew(idxNon Negat ive)<0)errNN= norm( max(0,-ynew(idxNon Negat ive)) ) / errwt;if errNN> rtolerr = errNN;NNreje ctSte p = true;endendelseerr = absh * norm((f * E) ./max(max(abs(y),abs(ynew)),thresh old),inf);if nonNeg ative && (err <= rtol) && any(ynew(idxNon Negat ive)<0)errNN= norm( max(0,-ynew(idxNon Negat ive)) ./ thresh oldNo nNega tive, inf);if errNN> rtolerr = errNN;NNreje ctSte p = true;endendend% Accept the soluti on only if the weight ed erroris no more than the % tolera nce rtol. Estima te an h that will yieldan errorof rtol ong this step, as the case may be, % the next step or the next try at takin% and use 0.8 of this valueto avoidfailur es.if err > rtol % Failed stepnfaile d = nfaile d + 1;if absh <= hminwarnin g('MATLAB:ode45:Integr ation TolNo tMet',['Failur e at t=%e. '...'Unable to meet integr ation tolera nceswithou t reduci ng '...'the step size belowthe smalle st valueallowe d (%e) '...'at time t.'],t,hmin);solver_outp ut = odefin alize(solver_name, sol,...output Fcn, output Args,...prints tats, [nsteps, nfaile d,nfeval s],...nout, tout, yout,...haveEv entFc n, teout,yeout,ieout,... {f3d,idxNon Negat ive});if nargou t > 0vararg out = solver_outp ut;endreturn;endif nofail ednofail ed = false;if NNreje ctSte pabsh = max(hmin, 0.5*absh);elseabsh = max(hmin, absh * max(0.1, 0.8*(rtol/err)^pow));endelseabsh = max(hmin, 0.5 * absh);endh = tdir * absh;done = false;else% Succes sfulstepNNrese t_f7= false;if nonNeg ative && any(ynew(idxNon Negat ive)<0)ynew(idxNon Negat ive) = max(ynew(idxNon Negat ive),0);if normco ntrolnormyn ew = norm(ynew);endNNrese t_f7= true;endbreak;endendnsteps = nsteps + 1;if haveEv entFc n[te,ye,ie,valt,stop] = ...odezer o(@ntrp45,eventF cn,eventA rgs,valt,t,y,tnew,ynew,t0,h,f,idxNon Negative);if ~isempt y(te)if output_sol|| (nargou t > 2)teout= [teout, te];yeout= [yeout, ye];ieout= [ieout, ie];endif stop % Stop on a termin al event.% Adjust the interp olati on data to [t te(end)].% Update the deriva tives usingthe interp olati ng polyno mial.taux = t + (te(end) - t)*A;[~,f(:,2:7)] = ntrp45(taux,t,y,[],[],h,f,idxNon Negat ive);tnew = te(end);ynew = ye(:,end);h = tnew - t;done = true;endendendif output_solnout = nout + 1;if nout > length(tout)tout = [tout, zeros(1,chunk,dataTy pe)]; % requir es chunk>= refine yout = [yout, zeros(neq,chunk,dataTy pe)];f3d = cat(3,f3d,zeros(neq,7,chunk,dataTy pe));endtout(nout) = tnew;yout(:,nout) = ynew;f3d(:,:,nout) = f;endif output_ty || haveOu tputF cnswitch output Atcase'Solver Steps'% comput ed points, no refine mentnout_n ew = 1;tout_n ew = tnew;yout_n ew = ynew;case'Refine dStep s'% comput ed points, with refine menttref = t + (tnew-t)*S;nout_n ew = refine;tout_n ew = [tref, tnew];yout_n ew = [ntrp45(tref,t,y,[],[],h,f,idxNon Negat ive), ynew];case'Reques tedPo ints'% output only at tspanpointsnout_n ew = 0;tout_n ew = [];yout_n ew = [];whilenext <= ntspanif tdir * (tnew - tspan(next)) < 0if haveEv entFc n && stop % output tstop,ystopnout_n ew = nout_n ew + 1;tout_n ew = [tout_n ew, tnew];yout_n ew = [yout_n ew, ynew];endbreak;endnout_n ew = nout_n ew + 1;tout_n ew = [tout_n ew, tspan(next)];if tspan(next) == tnewyout_n ew = [yout_n ew, ynew];elseyout_n ew = [yout_n ew,ntrp45(tspan(next),t,y,[],[],h,f,idxNon Negat ive)];endnext = next + 1;endendif nout_n ew > 0if output_tyoldnou t = nout;nout = nout + nout_n ew;if nout > length(tout)tout = [tout, zeros(1,chunk,dataTy pe)]; % requir es chunk>= refineyout = [yout, zeros(neq,chunk,dataTy pe)];endidx = oldnou t+1:nout;tout(idx) = tout_n ew;yout(:,idx) = yout_n ew;endif haveOu tputF cnstop =feval(output Fcn,tout_n ew,yout_n ew(output s,:),'',output Args{:});if stopdone = true;endendendendif donebreakend% If therewere no failur es comput e a new h.if nofail ed% Note that absh may shrink by 0.8, and that err may be 0.temp = 1.25*(err/rtol)^pow;if temp > 0.2absh = absh / temp;elseabsh = 5.0*absh;endend% Advanc e the integr ation one step.t = tnew;y = ynew;if normco ntrolnormy= normyn ew;endif NNrese t_f7% Used f7 for unpert urbed soluti on to interp olate.% Now resetf7 to move alongconstr aint.f(:,7) = feval(odeFcn,tnew,ynew,odeArg s{:});nfeval s = nfeval s + 1;endf(:,1) = f(:,7); % Alread y have f(tnew,ynew)endsolver_outp ut = odefin alize(solver_name, sol,...output Fcn, output Args,...prints tats, [nsteps, nfaile d, nfeval s],...nout, tout, yout,...haveEv entFc n, teout, yeout, ieout,...{f3d,idxNon Negat ive});if nargou t > 0vararg out = solver_outp ut;end。
matlab的ode函数
matlab的ode函数在MATLAB中,ODE函数(ordinary differential equation)用于求解常微分方程(ordinary differential equations,ODEs)的数值解。
ODE函数在MATLAB的“ode”命令下调用,有多种不同类型的ODE求解器可供选择。
ODE函数的语法如下:[t, y] = ode45(odefun, tspan, y0)其中- “ode45”是一种常用的ODE求解器,可以用于求解非刚性的一阶或高阶常微分方程。
- “odefun”是一个函数句柄,表示待求解的ODE,其形式为dy/dt= f(t, y)。
该函数需要接受两个输入参数:自变量t和因变量y,并输出对应的导数值。
- “tspan”是一个包含两个元素的向量,表示自变量t的范围。
-“y0”是一个包含初始条件的列向量,表示因变量y在自变量t的初始值。
ODE函数的输出包括两个变量:- “t”是一个列向量,表示自变量t的离散值。
这些值等距地分布在tspan范围内。
-“y”是一个矩阵,每一列代表因变量y在相应t值处的数值解。
除了ode45之外,MATLAB还提供了其他常用的ODE求解器,包括ode23、ode113、ode15s、ode23s等。
这些求解器根据不同的算法和精度要求进行了优化,可根据具体问题的特点选择适当的求解器。
在使用ODE函数时,需要定义一个ODE函数句柄,作为输入参数传递给ODE求解器。
此函数句柄需要编写对应的ODE方程,并确保正确地输入输出导数值。
以下是一个示例ODE函数的编写过程:function dydt = myODE(t, y)dydt = 2 * y; % 示例ODE:dy/dt = 2*y然后,可以调用ODE求解器来求解该ODE:这将返回自变量t的离散值和对应的因变量y的数值解。
通过使用ODE函数,用户可以方便地在MATLAB环境中求解常微分方程,并获取其数值解。
matlab ode45函数用法
MATLAB ODE45函数用法在MATLAB中,ODE45函数是用于求解常微分方程(ODE)的一种常用工具。
它采用龙格-库塔法(Runge-Kutta)来数值求解微分方程,通常适用于非刚性的微分方程问题。
在本文中,我们将深入探讨ODE45函数的用法,并通过具体例子来演示它的实际应用。
1. ODE45函数概述ODE45函数的基本语法如下:```matlab[t, y] = ode45(@odefun, tspan, y0)```其中,@odefun是一个用户自定义的函数,用于定义微分方程的形式;tspan是时间范围;y0是初始条件。
这个函数返回两个参数:t是时间向量,y是对应时间点的解向量。
2. ODE45函数的详细用法2.1. 自定义微分方程函数在使用ODE45函数之前,我们需要先定义微分方程的形式。
通常,我们将微分方程表示为一个函数的形式,例如:```matlabfunction dydt = odefun(t, y)dydt = % 根据微分方程的具体形式对dydt进行计算end```在这个函数中,dydt表示微分方程的导数,t表示时间,y表示状态变量。
我们需要根据具体的微分方程形式来计算dydt的值。
2.2. 设定时间范围和初始条件在使用ODE45函数时,我们需要设定时间范围和初始条件。
时间范围可以用一个包含起始时间和结束时间的向量来表示,例如tspan = [0, 10];初始条件则是微分方程在起始时间点的状态变量值,例如y0 = 1。
2.3. 求解微分方程并获取结果一旦定义了ODE45函数的参数,我们就可以用它来求解微分方程了。
调用ODE45函数后,它将返回时间向量t和对应时间点的解向量y,我们可以利用这些结果来进行进一步的分析和应用。
3. ODE45函数的实际案例为了更好地理解ODE45函数的用法,让我们通过一个具体的案例来演示。
假设我们有一个简单的一阶微分方程:```matlabfunction dydt = odefun(t, y)dydt = -2*t*y;end```我们希望求解该微分方程在时间范围tspan = [0, 5],初始条件y0 = 1的情况下的解。
matlabode45函数用法
matlabode45函数用法matlabode45函数用法MATLAB ode45函数是一种精确而快速的常微分方程求解器,它可以解决给定初值问题。
其特性主要有:能处理常微分方程组;支持多种初值条件;可以使用Runge-Kutta 方法及其变体进行数值积分;自动调整步长以提高解精度;支持二次函数等。
1. matlabode45函数格式matlabode45函数的格式为[t,y]=ode45(@func,tspan,y0),其中@func表示一个名为func的函数,它定义了待求解方程;tspan表示时间区间[t0,t1],y0表示随机初始时刻的值。
2. 调用matlabode45函数的步骤(1)首先定义待求解的常微分方程,一般形式为dy/dt=f(t,y);(2)将待求解的常微分方程写成一个函数func,并用MATLAB的文本编辑器打开;(3)在MATLAB的命令窗口中调用ode45函数,调用格式为[t,y]=ode45(@func,tspan,y0);(4)函数func包括输入、输出参数,输入参数t和y表示时间和函数量,输出参数dydt表示对应t和y的导数值;(5)在MATLAB中运行ode45函数,返回解的时间点t和函数值y;(6)将返回解的结果t和y用直方图、曲线图等图形方式表示出来,以便于更好地理解求解结果。
3. ode45函数的优点(1)ode45函数可以解决给定初值问题;(2)ode45函数可以处理常微分方程组;(3)ode45函数支持多种初值条件;(4)ode45函数可以使用Runge-Kutta方法及其变体进行数值积分;(5)ode45函数可以自动调整步长以提高解精度;(6)ode45函数支持二次函数等。
4. ode45函数的应用(1)在科学研究中,ode45函数可以用于求解涉及到初值问题的常微分方程,如求解生物学方程、星系动力学方程、天体运动方程等;(2)在工程领域,可以使用ode45函数求解涉及到初值问题的常微分方程,如求解水动力学方程、热传导方程、声学方程等;(3)在物理学研究中,可以使用ode45函数求解涉及到初值问题的常微分方程,如求解热力学方程、电磁学方程、流体动力学方程等。
ode45 matlab 用法
在本文中,我将为您介细介绍MATLAB中的ode45函数的用法。
ode45函数是MATLAB中常用的求解常微分方程(ODE)的函数,可以对一阶或高阶ODE进行求解,并且能够处理刚体动力学、化学反应动力学、电路等各种领域的问题。
我将从ode45函数的基本用法、参数设定、示例应用以及个人理解这几个方面展开讨论。
1. ode45函数的基本用法ode45函数是MATLAB中常用的求解ODE的函数。
其基本用法为:[t, y] = ode45(odefun, tspan, y0)其中,odefun为自定义的求解函数,tspan为时间范围,y0为初值条件。
ode45函数通过自适应步长Runge-Kutta法对ODE进行求解,得到时间t与对应的解y。
2. 参数设定在使用ode45函数时,需要设定求解的ODE函数odefun、时间范围tspan和初值条件y0。
还可以设定相对误差容限RelTol和绝对误差容限AbsTol,以控制求解的精度。
还可以通过设定事件函数、输出函数等对求解过程进行控制和监测。
3. 示例应用下面通过一个简单的例子来说明ode45函数的应用。
考虑一个简单的一阶ODE问题:dy/dt = -y,y(0) = 1其MATLAB代码如下:```matlabodefun = @(t, y) -y;tspan = [0, 5];y0 = 1;[t, y] = ode45(odefun, tspan, y0);plot(t, y, '-o');```这段代码首先定义了ODE函数odefun,然后设定时间范围tspan和初值条件y0,最后利用ode45函数求解ODE并绘制解y随时间t的图像。
4. 个人观点和理解在我看来,ode45函数是MATLAB中非常强大且常用的求解ODE的工具。
它能够高效地对各种类型的ODE进行求解,并且通过设定参数和监控函数,可以实现对求解过程的精确控制。
在工程领域和科学研究中,ode45函数的灵活性和高效性使其成为了不可或缺的工具。
ODE_45使用方法
ode45 Solve non-stiff differential equations, medium order method.[TOUT,YOUT] = ode45(ODEFUN,TSPAN,Y0) with TSPAN = [T0 TFINAL] integrates the system of differential equations y' = f(t,y) from time T0 to TFINALwith initial conditions Y0. ODEFUN is a function handle. For a scalar Tand a vector Y, ODEFUN(T,Y) must return a column vector correspondingto f(t,y). Each row in the solution array YOUT corresponds to a timereturned in the column vector TOUT. To obtain solutions at specifictimes T0,T1,...,TFINAL (all increasing or all decreasing), use TSPAN =[T0 T1 ... TFINAL].[TOUT,YOUT] = ode45(ODEFUN,TSPAN,Y0,OPTIONS) solves as above with default integration properties replaced by values in OPTIONS, an argument createdwith the ODESET function. See ODESET for details. Commonly used optionsare scalar relative error tolerance 'RelTol' (1e-3 by default) and vectorof absolute error tolerances 'AbsTol' (all components 1e-6 by default).If certain components of the solution must be non-negative, useODESET to set the 'NonNegative' property to the indices of thesecomponents.ode45 can solve problems M(t,y)*y' = f(t,y) with mass matrix M that isnonsingular. Use ODESET to set the 'Mass' property to a function handleMASS if MASS(T,Y) returns the value of the mass matrix. If the mass matrixis constant, the matrix can be used as the value of the 'Mass' option. Ifthe mass matrix does not depend on the state variable Y and the functionMASS is to be called with one input argument T, set 'MStateDependence' to 'none'. ODE15S and ODE23T can solve problems with singular mass matrices.[TOUT,YOUT,TE,YE,IE] = ode45(ODEFUN,TSPAN,Y0,OPTIONS) with the 'Events'property in OPTIONS set to a function handle EVENTS, solves as abovewhile also finding where functions of (T,Y), called event functions,are zero. For each function you specify whether the integration isto terminate at a zero and whether the direction of the zero crossingmatters. These are the three column vectors returned by EVENTS:[VALUE,ISTERMINAL,DIRECTION] = EVENTS(T,Y). For the I-th event function:VALUE(I) is the value of the function, ISTERMINAL(I)=1 if the integrationis to terminate at a zero of this event function and 0 otherwise.DIRECTION(I)=0 if all zeros are to be computed (the default), +1 if onlyzeros where the event function is increasing, and -1 if only zeros wherethe event function is decreasing. Output TE is a column vector of timesat which events occur. Rows of YE are the corresponding solutions, andindices in vector IE specify which event occurred.SOL = ode45(ODEFUN,[T0 TFINAL],Y0...) returns a structure that can beused with DEVAL to evaluate the solution or its first derivative atany point between T0 and TFINAL. The steps chosen by ode45 are returned in a row vector SOL.x. For each I, the column SOL.y(:,I) containsthe solution at SOL.x(I). If events were detected, SOL.xe is a row vectorof points at which events occurred. Columns of SOL.ye are the corresponding solutions, and indices in vector SOL.ie specify which event occurred.Example[t,y]=ode45(@vdp1,[0 20],[2 0]);plot(t,y(:,1));solves the system y' = vdp1(t,y), using the default relative error tolerance 1e-3 and the default absolute tolerance of 1e-6 for each component, and plots the first component of the solution.Class support for inputs TSPAN, Y0, and the result of ODEFUN(T,Y):float: double, singleSee also ode23, ode113, ode15s, ode23s, ode23t, ode23tb, ode15i,odeset, odeplot, odephas2, odephas3, odeprint, deval,odeexamples, rigidode, ballode, orbitode, function_handle.Reference page in Help browserdoc ode45。
matlab中 ODE45的用法 英文资料
y
Values of the solution to the problem (array). Each column of y is a different
dependent variable. The size of the array is length(t)-by-length(y0)
Specific examples of using ode45 now follow. Mfiles for these examples are in the body of this document and should also be available in the folder that contains this document.
Contents:
Syntax for ode45 ....................................................................................................................... 2 Integrating a single, first-order equation...................................................................................... 3 Getting the solution at particular values of the independent variable........................................... 4 Integrating a set of coupled first-order equations......................................................................... 4 Integrating a second-order initial-value problem (IVP)................................................................ 7 Integrating an Nth-order initial-value problem............................................................................ 8 Changing model parameters........................................................................................................ 9 Integrating a second-order boundary-value problem (BVP)........................................................ 11 Setting options in ode45 .......................................................................................................... 12 Going beyond ode45................................................................................................................. 13
关于ode45函数的说明
y0 y 1 x y2 ... yn 1
Dx是一个数组,其第一个元素Dx(1)表示dy0/dt 第二个元素Dx(2)表示dy1/dt 如此类推。
x也是一个数组,其第一个元素x(1)表示y0 第二个元素x(2)表示y1 如此类推。 根据这个关系,很容易可以把一阶微分方程组用 数组Dx与数组x的元素表示出来。例如(见下页)
dy0 f 0 t , y0 , y1 , y2 ,..., yn 1 dt dy1 f1 t , y0 , y1 , y2 ,..., yn 1 dt dy2 f 2 t , y0 , y1 , y2 ,..., yn 1 dt dyn 1 f n 1 t , y0 , y1 , y2 ,..., yn 1 dt
[T,Y]=ode45(‘odefun’,tspan,y0)
tspan为求解区间 y0为初始条件
(1)根据问题所属学科中的规律、定律、公式, 用微分方程与初始条件进行描述。
F y , y , y ,..., y ,t 0 微分方程
n
初始条件 y 0 c0 , y 0 c1 ,..., y
(3)根据(1)和(2)的结果,编写计算导数的 M函数文件。
2016新编matlabode45和矩阵生成有向网络图
Matlab中解常微分方程的ode45ode是专门用于解微分方程的功能函数,他有ode23,ode45,ode23s等等,采用的是Runge-Kutta算法。
ode45表示采用四阶,五阶runge-kutta单步算法,截断误差为(Δx)^3。
解决的是Nonstiff(非刚性)的常微分方程.是解决数值解问题的首选方法,若长时间没结果,应该就是刚性的,换用ode23来解.其他几个也是类似的用法使用方法[T,Y] = ode45(odefun,tspan,y0)odefun 是函数句柄,可以是函数文件名,匿名函数句柄或内联函数名tspan 是区间[t0 tf] 或者一系列散点[t0,t1,...,tf]y0 是初始值向量T 返回列向量的时间点Y 返回对应T的求解列向量[T,Y] = ode45(odefun,tspan,y0,options)options 是求解参数设置,可以用odeset在计算前设定误差,输出参数,事件等[T,Y,TE,YE,IE] =ode45(odefun,tspan,y0,options)每组(t,Y)之产生称为事件函数。
每次均会检查是否函数等于零。
并决定是否在零时终止运算。
这可以在函数中之特性上设定。
例如以events 或@events产生一函数。
[value, isterminal,direction]=events(t,y)其中,value(i)为函数之值,isterminal(i)=1时运算在等于零时停止,=0时继续;direction(i)=0时所有零时均需计算(默认值),+1在事件函数增加时等于零,-1在事件函数减少时等于零等状况。
此外,TE, YE, IE则分别为事件发生之时间,事件发生时之答案及事件函数消失时之指针i。
sol =ode45(odefun,[t0 tf],y0...) sol 结构体输出结果应用举例1 求解一阶常微分方程程序:) (y+3*t)/t^2; %定义函数tspan=[1 4]; %求解区间y0=-2; %初值[t,y]=ode45(odefun,tspan,y0);plot(t,y) %作图title('t^2y''=y+3t,y(1)=-2,1<t<4')legend('t^2y''=y+3t') xlabel('t')ylabel('y') % 精确解% dsolve('t^2*Dy=y+3*t','y(1)=-2')% ans =% (3*Ei(1) - 2*exp(1))/exp(1/t) - (3*Ei(1/t))/exp(1/t)2 求解高阶常微分方程关键是将高阶转为一阶,odefun的书写.F(y,y',y''...y(n-1),t)=0用变量替换,y1=y,y2=y'...注意odefun方程定义为列向量dxdy=[y(1),y(2)....]程序:function Testode45tspan=[3.9 4.0]; %求解区间y0=[2 8]; %初值[t,x]=ode45(@odefun,tspan,y0);plot(t,x(:,1),'-o',t,x(:,2),'-*')legend('y1','y2')title('y'' ''=-t*y + e^t*y'' +3sin2t')xlabel('t') y label('y')function y=odefun(t,x)y=zeros(2,1); % 列向量y(1)=x(2);y(2)=-t*x(1)+exp(t)*x(2)+3*sin(2*t);endendmatlab练习程序(矩阵生成有向网络图)早知道有向图和无向图差别没有想象中的大我就写到一起了。
matlab-function里ode45函数求解微分方程
matlab-function里ode45函数求解微分方程ode45函数可以用于求解形如y'=f(t,y)的一阶常微分方程或者形如y''=f(t,y,y')的二阶常微分方程,其中f是一个函数,t是自变量,y是因变量。
下面是一个使用ode45函数求解一阶常微分方程的例子:
matlab
function dydt = myfun(t,y)
dydt = -2*y + sin(t);
end
[t,y] = ode45(@myfun,[0,5],1);
plot(t,y)
在这个例子中,myfun函数定义了一个微分方程dydt=-2*y+sin(t),其中t是自变量,y是因变量。
ode45函数的第一个参数是myfun,告诉它要求解的微分方程是什么。
第二个参数是一个具有两个元素的向量[0,5],指定了求解的时间范围。
第三个参数是给出了y(0)=1的初始条件。
最后的结果是得到了一个y随时间变化的图像。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Bucknell University Using ODE45MATLAB Help MATLAB's standard solver for ordinary differential equations (ODEs) is the function ode45. This function implements a Runge-Kutta method with a variable time step for efficient computation.ode45 id designed to handle the following general problemd dt t t o o y f y y y ==(,)()[1]where t is the independent variable (time, position, volume) and y is a vector of dependent variables (temperature, position, concentrations) to be found. The mathematical problem is specified when the vector of functions on the right-hand side of Eq. [1], f y (,)t , is set and the initial conditions, y =y o at time t o , are specified.The notes here apply to versions of MATLAB above 5.0 and cover the basics of using the function ode45. For more information on this and other ODE solvers in MATLAB, see the on-line help.Contents:Syntax for ode45 (2)Integrating a single, first-order equation (3)Getting the solution at particular values of the independent variable (4)Integrating a set of coupled first-order equations (4)Integrating a second-order initial-value problem (IVP) (7)Integrating an N th-order initial-value problem (8)Changing model parameters (9)Integrating a second-order boundary-value problem (BVP)........................................................ 11Setting options in ode45.......................................................................................................... 12Going beyond ode45.. (13)Syntax for ode45ode45 may be invoked from the command line via[t,y] = ode45('fname', tspan, y0, opts)wherefname name of the function Mfile used to evaluate the right-hand-side function in Eq. [1] ata given value of the independent variable and dependent variable(s) (string). Thefunction definition line usually has the formfunction dydt = fname(t,y)The output variable (dydt) must be a vector with the same size as y. Note that theindependent variable (t here) must be included in the input argument list even if itdoes not explicitly appear in the expressions used to generate dydt.tspan2-element vector defining the range of integration ([to tf]) though variations are possible.y0vector of initial conditions for the dependent variable. There should be as many initial conditions as there are dependent variables.opts a MATLAB structure variable that allows you to control the details of computation (if you want to). This argument is optional and, if not provided, ode45 will usedefault values (see the examples below).t Value of the independent variable at which the solution array (y) is calculated. Note that by default this will not be a uniformly distributed set of values.y Values of the solution to the problem (array). Each column of y is a different dependent variable. The size of the array is length(t)-by-length(y0)Specific examples of using ode45 now follow. Mfiles for these examples are in the body of this document and should also be available in the folder that contains this document.Integrating a single, first-order equ ationThe height of fluid in a tank (h(t)) whose outlet flow is dependent on the pressure head (height of fluid) inside the tank and whose inlet flow is a function of time may be modeled via the equationdh dtt h h ho=−=αβ()()0[2]Find the solution, h(t), for 030<<t if the following values for the parameters are given.Input flow: α()sin()t t=+104β=2ho=1Step 1: Identify f t y(,) and write a MATLAB function Mfile to evaluate it.In this case, we have time as the independent variable and the tank height as the (single) dependent variable. Thus, we havef t y f t h t h(,)(,)()→=−αβ[3]From the given information for this problem, the required Mfile, named tankfill.m, isfunction dhdt = tankfill(t,h)% RHS function for tank-fill problemA = 10 + 4*sin(t);% alpha(t)H = 2*sqrt(h);% beta*sqrt(h)dhdt = A - H;% eof - tankfill.mStep 2: Use ode45 to solve the problemThe initial condition has the height at 1 for t = 0 and we want to integrate until t = 30. The following set of commands show explicitly how the solution is put together.>> tspan = [0 30];(integration range)>> h0 = 1;(initial condition, h(0))>> [t,h] = ode45('tankfill',tspan,h0);(solve the problem)Step 3: Look at the solutionThe solution can be viewed via the plot command as in>> plot(t,h)The "curve" is a little choppy though it is accurate to the default relative tolerance (0.001). Note that the places where the solution is given are not uniformly spread out. See the next section for improving appearances.Getting the solu tion at particu lar valu es of the independent variableode45 uses a variable-step-length algorithm to find the solution for a given ODE. Thus, ode45varies the size of the step of the independent variable in order to meet the accuracy you specify at any particular point along the solution. If ode45 can take "big" steps and still meet this accuracy, it will do so and will therefore move quickly through regions where the solution does not "change"greatly. In regions where the solution changes more rapidly, ode45 will take "smaller" steps. While this strategy is good from an efficiency or speed point of view, it means that the solution does not appear at a fixed set of values for the independent variable (as a fixed-step method would) and sometimes the solution curves look a little ragged.The simplest way to improve on the density of solution points is to modify the input tspan from a 2-element vector to an N -element vector via something like>> tspan = linspace(to,tf,500)’;and use this new version in the input list to ode45.Smoother curves can also be generated by interpolation (spline interpolation usually works nicely).For example, if you wanted a smoother result from the solution for the tank-fill problem, you might do the following>> ti = linspace(tspan(1),tspan(2),300);(300 points - you could use more)>> hi = spline(t,h,ti);>> plot(t,h,’o’,ti,hi);The interpolated curve smoothes out the rough edges caused by simply connecting the data points (which is what plot does) and so makes the graph more appealing, in a visual sense.Integrating a set of cou pled first-order equ ationsChemical-kinetics problems often lead to sets of coupled, first-order ODEs. For example, consider the reaction networkA B C ↔→[4]Assuming a first-order reaction-rate expression for each transformation, material balances for each species lead to the following set of ODEs:dA dt k A k B dB dt k A k B k B dC dtk B =−+=−−=121233[5]with the initial conditions, A A B B C C o o o (),(),()000===. Since the equations are coupled, youcannot solve each one separately and so must solve them simultaneously.The system in Eq. [5] can be put in the standard form for ode45 (Eq. [1]) by defining the vectors y ,y o and f asy y y f y = == =−+−+ A B C A B C t k y k y k y k k y k y o o o o ()(,)()011221123232[6]Solving the system represented by Eq. [6] is a simple extension of what was done for solving a single equation. We'll demonstrate the solution for the following situationk k k A B C o o o 12352110======Step 1: Write a function Mfile to evaluate the right-hand-side expressionThe primary difference here, compared to the single-equation case, is that the input variable y will be a vector . The first element of y represents the concentration of species A at a time t , and the second and third elements representing the concentrations of species B and C, respectively, at the sametime, t . This ordering of variables is defined by Eq. [6]. There is no "right" order to the variables but whatever order you do choose, use it consistently. We'll call the Mfile react.m . It looks like this:function dydt = react(t,y)% Solve the kinetics exampledydt = zeros(size(y));% Parameters - reaction-rate constantsk1 = 5; k2 = 2; k3 = 1;A = y(1);We'll be explicit about it here though you can do B = y(2);the calculations directly with the y -values.C = y(3);% Evaluate the RHS expressiondydt(1) = -k1*A + k2*B;dydt(2) = k1*A - (k2+k3)*B;dydt(3) = k3*B;% eof - react.mNote that the input arguments must be t and y (in that order) even though t is not explicitly used in the function.Step 2: Use ode45 to solve the problemNo time interval is given so we'll pick one (0 to 4) and see what the solution looks like. If a longer or shorter interval is needed, we can simply re-execute the function with a new value for the ending time. Following the outline for the single-equation problem, the call to ode45 is,>> [t,y] = ode45('react',[0 4],[1 0 0]);Note that the initial condition is provided directly in the call to ode45. You could also have defined a variable y0 prior to the call to ode45 and used that variable as an input.Take a moment to look at the outputs. The number of points at which the solution is known is >> length(t)Also consider the shape of the output variable y:>> size(y)Is the result as stated above (i.e., is it length(t)-by-length(y0))?Step 3: Look at the solutionIf you want to see the time-course of all species, use the command>> plot(t,y)The blue line will be the first column of y (species A). The green and red lines will be the second and third columns of y (species B and C, respectively).If you wanted to look at only one species (for example, species B), you would give the command >> plot(t,y(:,2))since the second column of y holds the information on species B.Integrating a second-order initial-valu e problem (IVP)A mass-spring-dashpot system can be modeled via the following second-order ODE˙˙˙()(),()˙()y cy y g t y y v y v o o ++====ω2000[7]In this model, c represents a retarding force proportional to the velocity of the mass, ω2 is thenatural frequency of the system and g (t ) is the forcing (or input) function. The initial conditions are the initial position (y o ) and initial velocity (v o ).ode45 is set up to handle only first-order equations and so a method is needed to convert this second-order equation into one (or more) first-order equations which are equivalent. The conversion is accomplished through a technique called "reduction of order". We'll illustrate the solution for the particular set of conditionsc y v g t t =====520100ω()()()sin()Step1: Define the components of a vector p =[]p p 12T as follows:p yp y12==˙[8]Step 2: Form the first derivatives of each of the components of pUsing the given differential equation, we can write a system of first-order equations as˙˙˙˙˙()˙()py p py g t cy y g t cp p 1222221====−−=−−ωω[9]In writing the expression for the second component, we've used the governing ODE (Eq. [7]).Step 3: Cast the problem in the format needed to use ode45.˙()(,)(,)(,)p p p p f p == =−− = =d dt d dt p p p g t cp p f t f t t 12222112ω[10]Step 4: Collect the initial conditions into a single vectorp p ()()()()˙()0000012== = =o o o p p y y y v [11]Step 5: Apply ode45 to solve the system of equationsThe Mfile for the RHS function for this problem will be called spring.m . Here it is:function pdot = spring(t,p)% Spring example problem% Parameters - damping coefficient and natural frequencyc = 5; w = 2;g = sin(t); % forcing functionpdot = zeros(size(p));pdot(1) = p(2);pdot(2) = g - c*p(2) - (w^2)*p(1);% eof - spring.mThe call to ode45 is, for a solution interval of 0 to 20,>> p0 = [1 0];(initial position and velocity)>> [t,p] = ode45('spring',[0 20],p0);Step 6: Look at the resultsIf you wanted to look at only the displacement, you'd want to look at the first column of p (see the definition of p in the first step, Eq. [8]). Hence, you would give the command>> plot(t,p(:,1))An interesting plot for these sorts of problems is the phase-plane plot, a plot of the velocity of the mass versus its position. This plot is easily created from your solution via>> plot(p(:,1),p(:,2))Phase-plane plots are useful in analyzing general features of dynamic systems.Integrating an N th-order initial-valu e problemTo use ode45 to integrate an Nth-order ODE, you simply continue the process outlined in the section on integrating a 2nd-order ODE. The first element of the vector p is set to the dependent variable and then subsequent elements are defined as the derivatives of the dependent variable up to one less than the order of the equation. Finally, the initial conditions are collected into one vector to give the format presented in Eq. [1].For example, the 4th-order equationa d ydxbd ydxcd ydxddydxey443322++++=[12]would generate the first-order systemd dtpppppppbp cp dp ep a12342344321=−+++()/[13]which, along with an appropriate set of initial conditions would complete the set-up for ode45.Changing model parametersIn all the examples given above, the parameter values were given specific variables in the Mfile used to evaluate the RHS function (the model of the system). This is fine for one-shot cases and in instances where you don't anticipate a desire to change the parameters. However, this situation is not fine where you want to be able to change the parameters (e.g., change the damping coefficient in order to see the result in a phase-plane plot). One approach to changing parameters is to simply edit the file every time you want to make a change. While having the advantage of simplicity, this approach suffers from inflexibility, especially as the number of parameters and as the frequency of the changes increase. To get other parameters into the function, you need to use an expanded version of the syntax for ode45, one that allows “other” information to be provided to the derivative function when ode45 uses that function. This is most easily seen by an example (and by reading the on-line help on ode45).Step 1: Write the Mfile for the RHS function so that it allows more input variables. The parameter list starts after the dependent variable and after a required input called flag.For this example, we will re-write spring.m so that c and w are given their values via the function definition line. The altered Mfile isfunction pdot = spring2(t,p,flag,c,w)% Spring example problem% Parameters – c is the damping coefficient and% w is the natural frequencypdot = zeros(size(p));g = sin(t); % forcing functionpdot(1) = p(2);pdot(2) = g - c*p(2) - (w^2)*p(1);% eof – spring2.mStep 2: Write a driver script that implements your logic and allows you to set values of the parameters for the problem.The script created here will do the following1. Implement a loop thata. asks for values of the parametersb. solves the ODEc. plots the phase-plane view of the solution2. Exits if no inputs are givenCertainly more sophisticated scripts are possible but this has the essence of the idea. The script is called dospring.m and it is:%DOSPRING Interactive plotting of the phase-planewhile 1 % infinite loopC_SPRING = input('Damping coefficient [c]: ');if isempty(C_SPRING) % how to get outbreakendW_SPRING = input('Natural frequency [w]: ');[t,p] = ode45('spring2',[0 20],[1 0],[],C_SPRING,W_SPRING);plot(p(:,1),p(:,2))title('Phase-plane plot of results')xlabel('position')ylabel('velocity')end% eos - dospring.mNote the additions to the call to ode45. First, a placeholder for the “options” input is inserted (an empty array) so that “default” options are used. Then, the parameters for the model are provided in the order that they appear in the definition line of the RHS function.Try the script out and modify it (e.g., you could add the frequency and/or amplitude of the forcing function as something to be changed).Integrating a second-order bou ndary-valu e problem (BVP)ode45 was written to solve initial-value problems (IVPs). Hence it cannot be (directly) used to solve, for example, the following problem derived from a model of heat-transfer in a rod:d2y dx2−y=0y(0)=1dydx x=1=0[14]since the value of the derivative at x = 0 is not specified (it is known at x = 1, though). Equation [14] is a boundary-value problem (BVP) and is common in models based on transport phenomena (heat transfer, mass transfer and fluid mechanics).All is not lost because one way to solve a BVP is to pretend it is an IVP. To make up for the lack of knowledge of the derivative at the initial point, you can guess a value, do the integration and then check yourself by seeing how close you are to meeting the conditions at the other end of the interval. When you have guessed the right starting values, you have the solution to the problem. This approach is sometimes called the "shooting method" by analogy to the ballistics problem of landing an artillery shell on a target by specifying only it's set-up (powder charge and angle of the barrel).Step 1: Set up the problem so that ode45 can solve itUsing the approach of turning a second order equation into a pair of coupled first-order equations, we haved dxpppp v12211==p()[15]where v has been used to represent the (unknown) value of the derivative at x = 0. The Mfile used to evaluate the RHS is as followsfunction dpdx = hotrod(x,p)% Hot-rod problem illustrating the shooting methoddpdx = zeros(size(p));dpdx(1) = p(2);dpdx(2) = p(1);% eof - hotrod.mStep 2: Guess a value of the initial slope and integrate to x = 1The problem will be iterative so it's not likely that the first guess will be right. From the physics of the problem, the end of the rod (at x = 1) will be colder than the place we are starting from (x = 0) and so we'll guess a negative value for the initial slope.>> v = -1;>> [x,p] = ode45('hotrod',[0 1],[1 v]);The value of the derivative at x = 1 is the last value in the second column of p (why?). Thus, we can check the accuracy of the first guess via>> p(length(x),2)which I found to be -0.3679. That’s too low (it should be zero).Step 3: Iterate until the boundary condition at x = 1 is metYou can use brute force here if you have only one problem or you could finesse it by hooking the whole thing up to fzero and have fzero do the guessing. Here are my brute-force results:Value of v Slope at x = 1-1.0-0.3679-0.5-0.4037-0.75-0.0179-0.76-0.0025The trend is obvious and so the initial slope is around -0.76 (the exact value is -tanh(1) = -0.7611...). Using fzero would be a good alternative if this problem were to be solved many times over.Step 4: Look at the resultsEven though we are guessing the initial slope to solve the problem, it is the solution, y(x), that we are really interested in. This solution is in the first column of p and may be viewed via >> plot(x,p(:,1))Setting options in ode45The input opts is a MATLAB structure variable that con be used to control the performance of the various ODE-solvers in MATLAB. The most common option that you’ll likely want to alter is the accuracy to which solutions are computed. To make this process easy, a pair of functions are available – odeset for creating and changing options and odeget for displaying information on options. To see what the current settings are, try the command>> odesetDefault values for any setting are denoted by the braces, {}.MATLAB uses two accuracy measures for solving ODEs – the relative tolerance (RelTol in opts) and the absolute tolerance (AbsTol in opts). Each step in the integration is taken so that it satisfies the conditionError at step j yk jk k≤⋅max(,)RelTol AbsTolwhere the subscript k ranges over all the components of the solution vector at time step j. To alter the default settings, use commands such as>> oldOpts = odeset;>> newOpts = odeset(oldOpts,’RelTol’,1e-6)Information on the settings for the other options is available in the on-line help.Going beyond ode45The solver ode45 is not the be-all and end-all of ODE-solvers. While ode45 should be your first choice for integration, there are problems that the function performs poorly on or even fails on. In such cases, there are fallback solvers that are available. All these solvers use the same syntax asode45 (see page 2) but have options for handling more difficult or sophisticated problems.Here are some suggestions for handling non-standard ODE problems:• If accuracy you desire is not obtainable via ode45, try the function ode113. This solver uses a variable order method that may be able to improve over what ode45 does.• If ode45 is taking too long to compute a solution, your problem may be “stiff” (i.e., it involvesa system with a wide range of time constants). Try the function ode15s.• If your system of equations has the formMyf y ddtt=(,)where M is a (typically non-singular) matrix, try the function ode15s.You’ll find more information on these function in the on-line help and documentation. For example, try the on-line function reference (available through the command helpdesk) on any of the solvers noted above.。