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: ernst
Subject: Re: testing global variable from within a function
Date: Sun, 27 Jan 2013 21:08:09 +0100
User-agent: Mozilla/5.0 (X11; Linux i686; rv:15.0) Gecko/20120825 Thunderbird/15.0

Hi Juan, 
Thanks for the quick answer, but my problem remains. 
Let me describe the situation more clearly: 

I have a global variable, 

global x=1;% defined in octaverc

but is seems as if the function zeros() is invoked (by octave itself) before the global settings take effect. 
So I have to distinguish, whether zeros() is invoked by the user after initialization 
or before by octave itself. 

My naive idea was to check whether x is defined. 
So i tried exist('x','var') from within function zeros(). 

Then i realized that this returns false unless i declare global x within zeros(). 
But then it returns true because then, at least it seems to me so, 
octave interprets global x as defining x global. 

Ok, so i cannot check whether it is defined or not using exist: 
After declaration global x within zeros(), the variable x exists, before it doesn't. 

Any idea what do do? 

Greetings. 

Ernst 








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]