help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: testing global variable from within a function


From: Juan Pablo Carbajal
Subject: Re: testing global variable from within a function
Date: Sun, 27 Jan 2013 20:13:18 +0100

On Sun, Jan 27, 2013 at 7:51 PM, ernst <address@hidden> wrote:
> Hi all,
> I must check from within a function, whether a certain global variable
> 'myvarname' is defined.
>
> What i know is, that from outside the function i just try
> exist('myvarname', 'var').
> From within a function this does not work and i think
> this is because I shall declare the variable global before.
> But i have the impression, that 'global' defines a global variable, if
> it is not yet defined,
> otherwise makes the global variable already defined available.
> So, testing whether it is global, does not make any sense within a
> function,
> because testing after declaring global returns true, testing before
> returns false.
>
> What can i do?
>
> greetings, Ernst
>
> _______________________________________________
> Help-octave mailing list
> address@hidden
> https://mailman.cae.wisc.edu/listinfo/help-octave

"global" is a funny keyword in Matlab and therefore Octave.

For each scope you want a global to be "visible" you have to declare
it as global.
The following code would leave g2 untouched, though some people would
expect it to change

function y = test_global(x)
 global g1
 g2= x;
 y = g1;
endfunction

>global g1 g2
>g2=2;
>g1=-1;
>test_global(-2)
ans = -1
>g2
g2 = 2

If you want to access the global g2 you need to tell test_global that
g2 is a global variable.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]