Unrecognized function or variable 'ode4'.
조회 수: 23 (최근 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!
