Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share global variables across multiple octave scripts?

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?

like image 702
moondog Avatar asked Jan 11 '12 00:01

moondog


People also ask

Can global variables be accessed by multiple files?

A global variable is accessible to all functions in every source file where it is declared. To avoid problems: Initialization — if a global variable is declared in more than one source file in a library, it should be initialized in only one place or you will get a compiler error.

How do you declare global variables in multiple files?

The clean, reliable way to declare and define global variables is to use a header file to contain an extern declaration of the variable. The header is included by the one source file that defines the variable and by all the source files that reference the variable.

How do you declare a global variable in octave?

A variable is declared global by using a global declaration statement. The following statements are all global declarations. Note that the global qualifier extends only to the next end-of-statement indicator which could be a comma (' , '), semicolon (' ; '), or newline (' '\n' ').

Can we declare same variable in two times globally?

A variable or function can be declared any number of times, but it can be defined only once. (Remember the basic principle that you can't have two locations of the same variable or function).


1 Answers

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

like image 151
Steve Avatar answered Sep 28 '22 20:09

Steve