Reputation: 1577
Suppose I have three octave scripts a.m, b.m, c.m
, and two global variables x, y
. Is it possible to define these global variables in such a way that they can be shared across scripts? For example in a separate include file?
More Generally, how do global variables in GNU octave work?
Upvotes: 6
Views: 4907
Reputation: 21
Something like:
A file with global variables globals.m
with:
global my_global = 100;
And just use source
inside each file. For example:
source globals.m
global my_global
printf("%d\n", my_global);
Upvotes: 2
Reputation: 96
It seems you have to declare the variable global, and you also have to explicitly tell Octave that the variable you are referencing is in a different (global) scope.
in library.m
global x = 1;
in main.m
function ret = foo()
global x;
5 * x;
endfunction
foo() should return 5
Upvotes: 8
Reputation: 153942
Make a file called tmp.m and put the following code in it.
global x; %make a global variable called x
x = 5; %assign 5 to your global variable
tmp2(); %invoke another function
Make another file called tmp2.m and put the following code in there:
function tmp2()
%the following line is not optional, it tells this function go go out and get
%the global variable, otherwise, x will not be available.
global x
x
end
When you run the above code like this:
octave tmp.m
You get this output:
x = 5
The global variable x was preserved in tmp.m and retrieved in tmp2.m
Upvotes: 2
Reputation: 1577
Not sure this is the best solution, but I ended up creating a wrapper script, from which all the other scripts are called. I put my globals inside that wrapper script
Upvotes: 0