Infinite recursion in code to graph second order differential equations

3 ビュー (過去 30 日間)
Aleem Andrew
Aleem Andrew 2020 年 2 月 4 日
コメント済み: Aleem Andrew 2020 年 2 月 4 日
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

採用された回答

Bjorn Gustavsson
Bjorn Gustavsson 2020 年 2 月 4 日
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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by