fsolve Doesn't Recognize Input Variables
6 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Torsten
on 10 Mar 2017
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 Comments
Torsten
on 15 Mar 2017
solution = fsolve(@(x)myfun_Fanno_Flow(x(1),x(2),gamma,P2,Po1),guess,options)
Best wishes
Torsten.
More Answers (1)
Steven Lord
on 10 Mar 2017
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 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!