Take the 2-minute tour ×

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.


share|improve this question
Making a variable global, and assigning it a value (in your case a 2-D matrix) are completely separate and independent operations. –  Ben Voigt Mar 30 '12 at 5:08

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer

Your Answer


