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!