Stuck with function giving a zero output when calling global variables

조회 수: 10 (최근 30일)
Maxxy
Maxxy 2015년 2월 25일
댓글: Stephen23 2015년 2월 25일
Hi, I have defined global variables (all scalar) in my main script, along with their values.
When calling a function which calls these global variables, and assigning the required inputs, I get an output of zero. Here's my code:
function q1 = Hfcrsk(a,b)
global k Cpb Skbfn Cdil Tc0 Cstr Tsk0
Tc=a;
Tsk=b;
Skbf = ((Skbfn + (Cdil.*(Tc-Tc0)))./(1+(Cstr.*(Tsk0-Tsk))));
q1 = (k.*(Tc-Tsk)) + (Skbf.*Cpb.*(Tc-Tsk));
Calling Hfcrsk(30,35) for example always gives a 0 output.
Please help!!! Thanks:)
  댓글 수: 1
Stephen23
Stephen23 2015년 2월 25일
Which makes this situation a classic example of why using globals is a bad idea: it means that any of those variables can be changed somewhere at some point by another function and there is no easy way to know when this happens:
To quote from the first link, Doug Hull: "I have never seen MATLAB code where globals were the right thing to do". And MattFig: "Those beginners (at my work) who use these constructs end up calling me to come fix their mess a few months down the road". And Jan Simon: "these commands cause more problems than they solve".

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

채택된 답변

Guillaume
Guillaume 2015년 2월 25일
편집: Guillaume 2015년 2월 25일
You get a zero output most likely because one of your global is zero when you call your function. Put a breakpoint on the skbf = ... line and look at the value of your global when it's hit.
There's a very good reason that global are despised and it's that it's near impossible to keep track of where they're being modified. 99% of the time there are much better solutions than globals.
In you case I'd just pass around a structure with fields k, Cpb, Skbfn, etc. (and actually I'd give then some names that actually mean something) and pass that structure to the functions that need it.

추가 답변 (0개)

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by