MATLAB: Infinite recursion in code to graph second order differential equations

matlab mathworks

I am trying to implement the sample code from a section titled Pass Extra Parameters to ODE Function in an article on second order differential equations: https://www.mathworks.com/help/matlab/ref/ode45.html
When I try to execute the following code, I get an error message saying there is likely an infinite recursion in the program.
function dydt = odefcn(t,y,A,B)
A = 1;
B = 2;
tspan = [0 5];
y0 = [0 0.01];
[t,y] = ode45(@(t,y) odefcn(t,y,A,B), tspan, y0);
dydt = zeros(2,1);
dydt(1) = y(2);
dydt(2) = (A/B)*t.*y(1);
plot(t,y(:,1),'-o',t,y(:,2),'-.')
end

Best Answer

Let's analyse what's happening here.
When you call odefcn from the command-line
1, the first thing matlab does is to overwrite whatever values you've given to A and B.
2, then you define a time-span and initial-values.
3, after that the function calls ode45 with a function-handle to odefcn,
4, after a few set-up operations in ode45
5, the nex thing thing ode45 does is to call odefcn - go to step #1
There is nothing breaking this loop until you get some complaints about recursion extending too deep.
You might want to make the ODE-definition a subfunction of your main function. Something like this:
function dydt = odeproject(t,y,A,B)
if nargin < 3 || isempty(A)
A = 1;
end
if nargin < 4 || isempty(B)
B = 2;
end
tspan = [0 5];
y0 = [0 0.01];
[t,y] = ode45(@(t,y) odefcn(t,y,A,B), tspan, y0);
plot(t,y(:,1),'-o',t,y(:,2),'-.')
end
function dydt = odefcn(t,y,A,B)
dydt = zeros(2,1);
dydt(1) = y(2);
dydt(2) = (A/B)*t*y(1);
end
That way when the ode45 call starts to evaluate the ode-function it will call the odefcn defined in the function, which now cleanly and neatly returns some values of dydt and does nothing else.
HTH