From bug-octave-request at bevo dot che dot wisc dot edu Tue Nov 18 03:01:57 1997 Subject: Initial value of global variable From: "John W. Eaton" To: Maximilian Pitschi cc: bug-octave at bevo dot che dot wisc dot edu Date: Tue, 18 Nov 1997 02:59:28 -0600 On 18-Nov-1997, Maximilian Pitschi wrote: | In matlab, the initial value of a global variable | is the empty matrix, []. In octave (with --traditional), such a | variable is not defined. If you are using Matlab, what is the proper way to initialize a global variable only if it doesn't already have a value? It seems that global foo if (isempty (foo)) foo = initial_foo_value; end will not work if `[]' is among the valid values for foo. For example, function f () global foo if (isempty (foo)) foo = 1; end if (foo == []) do_empty_foo_thing (); else do_nonempty_foo_thing (); end global foo f () ## do nonempty foo thing by default. foo = [] f () ## I really wanted to do the empty foo thing! Would I really have to use another variable to keep track of whether `foo' should be initialized, or am I missing something here? In any case, I'm considering making this change, along with making statements like global foo = initial_foo_value; only perform the assignment if the global foo does not already have a value. Then I could write the above code like this: function f () global foo = 1 if (foo == []) do_empty_foo_thing (); else do_nonempty_foo_thing (); endif endfunction global foo f () ## do nonempty foo thing by default. foo = [] f () ## do the empty foo thing now. and get the results I expect. The unfortunate side-effect is that if you are using global variables to keep track of some state information that is common to several subroutines (see Octave's multiplot M-files, for example) and you write something like function f () global foo = 1; ... end function g () global foo = 2; ... end you might get unpredictible results depending on the order the functions are called. Comments? Thanks, jwe