[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
RE: setting global variables
From: |
Richardson, Anthony |
Subject: |
RE: setting global variables |
Date: |
Fri, 26 Oct 2018 18:05:59 +0000 |
> To: Help GNU Octave <address@hidden>
> Subject: setting global variables
>
> I have been using the "global" directive to set up some (around 50) global
> variables in a script. However in order to access them from functions in the
> > same script, I need to define them as global again or they are not defined
> in the function.
> Seems a bit redundant to me--is there some way to define variables share
> by all functions just once?
>
> Thanks
> Fritz
You can achieve a similar effect (although perhaps not quite as convenient) by
using a persistent struct inside a data retrieval function. I use a function
named simState() for this purpose.
To define and set the value of variable from within one function or script:
simState("TMAX", 1200.)
Then to retrieve the value from within any other function:
TMAX = simState("TMAX")
I have included simState() below. I use it for a purpose like what you
describe. I want to access a global variable from multiple functions. Note
that I retrieve a copy of the "global" value. If I want to change the global
value, I need to use simState("TMAX", newvalue).
Tony Richardson
function v = simState(key, val)
persistent state;
if (nargin == 0)
% Return the entire struct
v = state;
elseif (nargin == 1)
% Return a particular field from the struct
v = state.(key);
elseif (nargin == 2)
% Set a key value (key must be a string)
state.(key) = val;
v = val;
end
end