How can I use variables defined within a parent function in nested functions?
1 view (last 30 days)
Show older comments
I have a parent function and 2 inner (nested) functions. Nested1 defines a differential equation. Nested2 defines another differential equation which is a function of the outputs of the first equation, but solved backwards in time.
I am able to use the variables of the parent function in Nested1, but not in nested2. In other words, the variables of the parent function are not read by Nested2. I need the variables defined in the parent function to be used in both inner functions.
Your help in this would be much appreciated.
Many thanks.
function parent
% I have defined some variables here
[t,y]= ode45(@ode1_solve, tspan, Init_cond_1); %Solves the diff.eqn. of Nested1
[tau,x]= ode45(@ode2_solve, tspan1, Init_cond_2); %Solves diff.eqn. of Nested2
function Nested1 = ode1_solve(t,y)
%Differential equation1
end
function Nested2 = ode2_solve(tau,x,y)
%Differential equation2
end
end
0 Comments
Answers (1)
Walter Roberson
on 9 Dec 2016
Your line
[tau,x]= ode45(@ode2_solve, tspan1, Init_cond_2); %Solves diff.eqn. of Nested2
needs to be
[tau,x]= ode45(@(tau,x) ode2_solve(tau,x,y), tspan1, Init_cond_2); %Solves diff.eqn. of Nested2
2 Comments
Walter Roberson
on 9 Dec 2016
I think I need to see the code. Any variable that you assign to in the main function before you define the nested function should be visible.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!