Unrecognized function or variable 'ode4'.
19 次查看(过去 30 天)
显示 更早的评论
I am trying to use ode4 to validate with the Runge-Kutta method, but keep getiing this error when I call ode4 "Unrecognized function or variable 'ode4'."
h=0.1; % step size
x = 0:h:60;
%y(1) = [-0.5;0.3;0.2];
y(1) = -0.5;
F_xy = @(t) -3*cos(t/2) + 4*sin(t/2) + 1;
for i=1:(length(x)-1) % calculation loop
k_1 = F_xy(x(i));
k_2 = F_xy(x(i)+ 0.5*h*k_1);
k_3 = F_xy((x(i)+0.5*h*k_2));
k_4 = F_xy((x(i)+k_3*h));
y(i+1) = y(i) + (1/6)*(k_1+2*k_2+2*k_3+k_4)*h; % main equation
end
% validate using a decent ODE integrator
y0 = -0.5;
yx = ode4(F_xy, 0,h,60, y0)
plot(x,y,'o-', x, yx, '--')
0 个评论
采纳的回答
Walter Roberson
2022-10-11
编辑:Walter Roberson
2022-10-11
2 个评论
Walter Roberson
2022-10-11
Did you download the .zip file from that Question, and unzip it and place the directory on your MATLAB path ?
更多回答(1 个)
Torsten
2022-10-11
编辑:Torsten
2022-10-11
Look below at how k_1,...,k_4 must be computed in the case that your ODE function only depends on t, not y.
The classical Runge-Kutta boils down to the usual Simpson's rule.
h=0.1; % step size
x = 0:h:60;
%y(1) = [-0.5;0.3;0.2];
y(1) = -0.5;
F_xy = @(t) -3*cos(t/2) + 4*sin(t/2) + 1;
for i=1:(length(x)-1) % calculation loop
k_1 = F_xy(x(i));
k_2 = F_xy(x(i)+0.5*h);
k_3 = F_xy(x(i)+0.5*h);
k_4 = F_xy(x(i)+h);
y(i+1) = y(i) + (1/6)*(k_1+2*k_2+2*k_3+k_4)*h; % main equation
end
% validate using a decent ODE integrator
y0 = -0.5;
yx = ode4(@(t,y)F_xy(t), 0,h,60, y0);
plot(x,y,'o-', x, yx, '--')
function yout = ode4(F,t0,h,tfinal,y0)
% ODE4 Classical Runge-Kutta ODE solver.
% yout = ODE4(F,t0,h,tfinal,y0) uses the classical
% Runge-Kutta method with fixed step size h on the interval
% t0 <= t <= tfinal
% to solve
% dy/dt = F(t,y)
% with y(t0) = y0.
% Copyright 2014 - 2015 The MathWorks, Inc.
y = y0;
yout = y;
for t = t0 : h : tfinal-h
s1 = F(t,y);
s2 = F(t+h/2, y+h*s1/2);
s3 = F(t+h/2, y+h*s2/2);
s4 = F(t+h, y+h*s3);
y = y + h*(s1 + 2*s2 + 2*s3 + s4)/6;
yout = [yout; y]; %#ok<AGROW>
end
end
3 个评论
Walter Roberson
2022-10-11
The error between what two values? You cannot calculate the error unless you have an analytic solution.
h=0.1; % step size
x = 0:h:60;
y(1) = -0.5;
F_xy = @(t) -3*cos(t/2) + 4*sin(t/2) + 1;
syms t C
intF = int(F_xy(t), t)
eqn = subs(intF, t, 0) + C == y(1)
sol = solve(eqn)
intF = subs(intF + C, C, sol)
... that should be the analytic solution.
Torsten
2022-10-11
If you compare your code and ode4, you'll see that they are identical. So there should be no difference in the results.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Ordinary Differential Equations 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!