Reputation: 64730
I'm using Octave (or Matlab... I have both available), and trying to make a function that will setup my important variables used throughout the rest of my investigation.
However by default, variables declared in a function have a limited scope of that function only.
Is there a way to do this?
function defineBasicTerms()
global G = 9.807;
global F = [exp(1) 0; 0 1/exp(1)];
endfunction
such that after this function is called, variables G
and F
exist in the set of globally named variables?
Upvotes: 0
Views: 934
Reputation: 60780
Global variables require to be declared in each scope in which they are used. For example, if you have a function M-file defineBasicTerms.m
containing:
function defineBasicTerms
global G = 9.807;
end
then in the base workspace you can write:
defineBasicTerms
G % produces error: variable doesn't exist
global G
G % gives 9.807
Next, in a function that will use the constant G
:
function out = computeSomethingImportant(m)
global G
out = G * m;
end
That is, every time we want to use G
we need to do global G
to be access the global variable G
.
Note that this is a very dangerous situation. Two things can go wrong:
Some function assigns to the global variable G
, changing its value for the rest of the current session. It is really hard to know that this has happened, but computeSomethingImportant
will return the wrong values from this point on, until we again call defineBasicTerms
.
We call computeSomethingImportant
before calling defineBasicTerms
during the session.
The established method in MATLAB (and by extension in Octave) to define a constant is through a function. Functions can be written to always return the same value (MATLAB has no other way to declare a variable to be constant), and functions are automatically available in all workspaces and all contexts (as long as the function is on the path of course).
In your example, we'd write an M-file function G.m
containing:
function value = G
value = 9.807;
end
Now, in the base workspace:
G % gives 9.807
The function that uses the constant G
now looks simply like this:
function out = computeSomethingImportant(m)
out = G * m;
end
Note that constants such as pi
are defined in this way in MATLAB and Octave.
You would have to write one function M-file for each of the constants you want to declare. There is an alternative method that involves a class with static values, so that all constants can be defined in a single file. The syntax then however becomes different, one would need to use constants.G
, or something like that, to access the content value.
Upvotes: 2