我试图在MatLab中为ODE实现Taylor方法:
我的代码(到目前为止)是这样的.
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。
我还尝试了另一种代码,它来自Matlab函数,但我不明白f应该如何进入代码,以及如何计算这个df。
9/taylor.m
由于使用此链接中的函数时出错,我得到:
>> 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);发布于 2015-06-26 23:30:48
这是一个数值方法,所以它需要数值函数。然而,它们中的一些是从函数f的导数中计算出来的。为此,需要进行符号微分。
相关的Matlab命令是symfun (创建符号函数)和matlabFunction (将符号函数转换为数字)。
到目前为止,你所拥有的代码似乎是无法挽救的。您需要从更接近基础的地方开始,例如,"Matlab索引从1开始“。因此,我将填补您链接的代码中的空白(df的计算)。这些评论应该能解释到底发生了什么。
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)https://stackoverflow.com/questions/31058000
复制相似问题