
Global Variables in Octave
In this lesson, I will explain how to use global variables in Octave.
So, what is a global variable? A global variable can be read from any part of the program, even within the functions of the program, without being passed as a parameter.
Let me give you a practical example.
To define a global variable, you use the global statement.
>> global a=1
Octave creates a new variable 'a' and assigns it the value of 1.
>> a
a = 1
To access the global variable 'a' within a function without passing it as a parameter, include the statement 'global a' within the function.
>> function f()
global a
a
endfunction
The function accesses the global variable even if it's not passed as a parameter.
>> f
a = 1
The function 'f()' can access the value of the global variable 'a', but cannot modify it.
How to check if a variable is global
To check if a variable is global, you can use the following function:
>> isglobal('a')
This function returns a value of 1 if the variable is global, and 0 if it is not global.
How to modify the value of a global variable
Once a variable has been initialized, you cannot initialize it again.
>> global a=1
>> global a=2
>> a
a = 1
If you want to assign a new value to it, you can do so in this way:
>> a=2
You can also modify the value of the global variable inside a function.
The new value of the global variable is accessible from any other part of the program.
How to delete a global variable
To delete a global variable, you can use the "clear" command.
>> clear('a')
If this Nigiara lesson has helped you, please continue to follow us.