泰勒方法ODE [英] Taylor Method ODE

查看:168
本文介绍了泰勒方法ODE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在MatLab中为ODE实现Taylor方法:

I am trying to implement the Taylor method for ODEs in MatLab:

我的代码(到目前为止)看起来像这样...

My code (so far) looks like this...

function [x,y] = TaylorEDO(f, a, b, n, y0)
% syms t
% x = sym('x(t)'); % x(t)
% f = (t^2)*x+x*(1-x);

h = (b - a)/n;

fprime = diff(f);
f2prime = diff(fprime);

y(0) = y0,
for i=1:n
    T((i-1)*h, y(i-1), n) = double(f((i-1)*h, y(i-1)))+(h/2)*fprime((i-1)*h, y(i-1))
    y(i+1) = w(i) + h*T(t(i), y(i), n); 

我试图使用符号变量,但是我不知道是否/何时必须使用double.

I was trying to use symbolic variables, but I don´t know if/when I have to use double.

我还尝试了其他代码,这些代码来自Matlab函数,但是我不明白f应该如何输入代码以及如何计算df.

I also tried this other code, which is from a Matlab function, but I do not understand how f should enter the code and how this df is calculated.

作为使用此链接中的函数的错误,我得到了:

As error using the function from this link, I got:

>> taylor('f',0,2,0,20)
Error using feval
Undefined function 'df' for input arguments of type 'double'.

Error in TaylorEDO (line 28)
  D = feval('df',tj,yj)

我在这里使用的是

 syms t
 x = sym('x(t)'); % x(t)
 f = (t^2)*x+x*(1-x);

推荐答案

这是一种数值方法,因此需要数值函数.但是,其中一些是根据函数f的导数计算的.为此,您需要符号区分.

This is a numerical method, so it needs numerical functions. However, some of them are computed from the derivatives of the function f. For that, you need symbolic differentiation.

相关的Matlab命令是symfun(创建符号函数)和matlabFunction(将符号函数转换为数值).

Relevant Matlab commands are symfun (create a symbolic function) and matlabFunction (convert a symbolic function to numerical).

到目前为止,您所拥有的代码似乎无法挽救.您需要从更接近基础的地方开始,例如"Matlab索引从1开始".因此,我将在您链接到的代码中填补空白(df的计算).这些评论应说明发生了什么情况.

The code you have so far doesn't seem salvageable. You need to start somewhere closer to basics, e.g., "Matlab indices begin at 1". So I'll fill the gap (computation of df) in the code you linked to. The comments should explain what is going on.

function [T,Y] = taylor(f,a,b,ya,m)
syms t y
dfs(1) = symfun(f, [t y]);                         % make sure that the function has 2 arguments, even if the user passes in something like 2*y
for k=1:3
    dfs(k+1) = diff(dfs(k),t)+f*diff(dfs(k),y);    % the idea of Taylor method: calculate the higher derivatives of solution from the ODE
end
df = matlabFunction(symfun(dfs,[t y]));            % convert to numerical function; again, make sure it has two variables

h = (b - a)/m;                                     % the rest is unchanged except one line
T = zeros(1,m+1);
Y = zeros(1,m+1);
T(1) = a;
Y(1) = ya;
for j=1:m
  tj = T(j);
  yj = Y(j);
  D = df(tj,yj);                                   % syntax change here; feval is unnecessary with the above approach to df
  Y(j+1) = yj + h*(D(1)+h*(D(2)/2+h*(D(3)/6+h*D(4)/24)));
  T(j+1) = a + h*j;
end
end

用法示例:

syms t y
[T, Y] = taylor(t*y, 0, 1, 2, 100); 
plot(T,Y)

这篇关于泰勒方法ODE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆