fsolve Doesn't Recognize Input Variables
조회 수: 6 (최근 30일)
이전 댓글 표시
I'm new to the fsolve command and learning how it works. Following examples from Help, I wrote the following in the child file:
function F = myfun(M)
F = ((1/M)*(((1+((gamma-1)/2)*M^2)/(1+((gamma-1)/2)))^((gamma+1)/2/(gamma-1))))-(Ae/Ath);
I then wrote the following in the parent file and executed the script:
Ath=0.289; %Throat area (m^2)
Ae=0.578; %Exit area (m^2)
gamma=1.37; %Specific heat ratio
guess=1E-12;
fsolve(@myfun,guess)
However, fsolve doesn't work until I replace the variable references (i.e., gamma, Ae, Ath) in the child file with actual numbers (e.g., replace gamma w/1.37, etc.). Why is this and how do I work around this? Someone said I had to elevate the variables (i.e., gamma, Ae, Ath) to "global variables." But I don't know what that means, how to do it, or why. Any insight would be greatly appreciated.
Thanks, M Ridzon
댓글 수: 0
채택된 답변
Torsten
2017년 3월 10일
Ath=0.289; %Throat area (m^2)
Ae=0.578; %Exit area (m^2)
gamma=1.37; %Specific heat ratio
guess=1E-12;
sol=fsolve(@(x)myfun(x,Ath,Ae,gamma),guess)
function F = myfun(M,Ath,Ae,gamma)
F = ((1/M)*(((1+((gamma-1)/2)*M^2)/(1+((gamma-1)/2)))^((gamma+1)/2/(gamma-1))))-(Ae/Ath);
Best wishes
Torsten.
댓글 수: 3
Torsten
2017년 3월 15일
solution = fsolve(@(x)myfun_Fanno_Flow(x(1),x(2),gamma,P2,Po1),guess,options)
Best wishes
Torsten.
추가 답변 (1개)
Steven Lord
2017년 3월 10일
That's correct. Functions have their own workspaces where the variables they have defined internally and the variables they received as input arguments when they are called "live". Because you neither defined the variable Ath in your myfun function's body nor passed it in as an input argument to myfun, it doesn't exist in that workspace and so you can't use it. [I'm deliberately omitting some of the more complicated details regarding workspaces and variable scoping; what I've listed is sufficient to answer the question.]
The approach Torsten used to solve this problem and make Ath visible inside the myfun function workspace is the first approach listed on this documentation page. Global variables is another solution, but they can lead to other complications so that documentation page recommends avoiding using them.
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!