フィルターのクリア

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

1 回表示 (過去 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 Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by