Unrecognized function or variable 'ode4'.
Show older comments
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, '--')
Accepted Answer
More Answers (1)
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 Comments
Khang Nguyen
on 11 Oct 2022
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
on 11 Oct 2022
If you compare your code and ode4, you'll see that they are identical. So there should be no difference in the results.
Categories
Find more on Ordinary Differential Equations in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!