Joebevo
Joebevo

Reputation: 163

What is the syntax for declaring a global 2-dimensional array in MATLAB?

What is the syntax for declaring a global 2-dimensional array in MATLAB?

I want the array to be blank, or uninitialized. That is, I want to be able to initialize it to some value later on using a for-loop. All the examples I have come across so far consist of initializing the array when it is declared. I find this rather tedious because my array might have to be a large one.

Thanks.

Upvotes: 1

Views: 3867

Answers (1)

Bill Cheatham
Bill Cheatham

Reputation: 11917

Declare a variable as global first before using it:

global my_glob_var;

MATLAB doesn't really support the concept of 'uninitialised' variables, but you can create an array of NaNs (not a number) to indicate that each value hasn't been assigned yet. The arguments to the nan function indicate the size of the NaN array you wish to create:

my_glob_var = nan(200, 200)

There are other similar functions in case you wish to initialise arrays of zeros, ones, Inf etc.

Then inside the functions you want to use it in, declare it as global again:

function my_function

global my_glob_var  % allows this function to use the global variable
my_glob_var         % outputs the variable to command 

As an aside, you note that you will "initialise it to some value later using a for-loop". Depending on how you are initialising the array, there may be a vectorised way to achieve this (i.e. without using a for-loop). Vectorised operations are usually much quicker in MATLAB.

Upvotes: 1

Related Questions