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

조회 수: 5 (최근 30일)
Karim Shawki
Karim Shawki 2016년 12월 9일
댓글: Walter Roberson 2016년 12월 9일
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

답변 (1개)

Walter Roberson
Walter Roberson 2016년 12월 9일
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
Karim Shawki
Karim Shawki 2016년 12월 9일
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
Walter Roberson
Walter Roberson 2016년 12월 9일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by