Declaring a global variable in MATLAB

Amit picture Amit · Feb 6, 2011 · Viewed 70.3k times · Source

Is there a way to declare global variables in MATLAB?

Please don't respond with:

global x y z;

Because I can also read the help files.

I've declared a global variable, x, and then done something like this:

function[x] = test()
    global x;
    test1();
end

Where the function test1() is defined as:

function test1()
    x = 5;
end

When I run test(), my output is x = []. Is there a way I can make it output the x=5, or whatever I define x to be in a separate function? In C, this would be an external variable, and I thought making it a global variable should accomplish just that.

Answer

gnovice picture gnovice · Feb 6, 2011

You need to declare x as a global variable in every scope (i.e. function/workspace) that you want it to be shared across. So, you need to write test1 as:

function test1()
  global x;
  x = 5;
end