Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using global variables in a function loaded from a script file

Tags:

gnu

matlab

octave

So I got this function:

function M = getA(X)
global h;
QPL96 =  h;
M = QPL96;
endfunction

Now:

octave:115> h
h =  0.10000
octave:116> getA(X)
ans = [](0x0)

Isn't that strange? Works as long as there isn't an expression involving h. Otherwise returns that garbage. Why can't I do this? Must I work around it by making h an argument?

like image 870
user1854885 Avatar asked Feb 03 '26 22:02

user1854885


1 Answers

You'll have to declare h as global everywhere you want to use the "global" h, and that includes your main body. So type global h at the prompt and you'll be fine. See the documentation. The following works fine for me:

octave> function M = getA(X)
> global h;
> M = h;
> endfunction
octave> h = 0.01
h =  0.0010000
octave> getA
ans = [](0x0)
octave> global h
octave> h
h = [](0x0)
octave> h = 0.01
h =  0.010000
octave> h
h =  0.010000
octave> getA
ans =  0.010000

But really, you shouldn't use global variables, that's really bad practice. Pass the variable as argument. If you find yourself passing the same group of variables, pass a struct, but still don't use global variables.

EDIT: this is the same question.

like image 131
carandraug Avatar answered Feb 06 '26 13:02

carandraug



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!