How can I use variables defined within a parent function in nested functions?

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

Answers (1)

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

Dear Walter,
Thanks for your answer. I have tried your suggestion but it hasn't worked for me. My problem is that the variables in the parent function cannot be used in the function nested2. However, there is no problem with accessing the parent function variables in Nested1. Is there a way I can access all the variables defined in the parent function in both nested functions?
Many thanks, Karim
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.

Sign in to comment.

Categories

Find more on Programming in Help Center and File Exchange

Asked:

on 9 Dec 2016

Commented:

on 9 Dec 2016

Community Treasure Hunt

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

Start Hunting!