Declaring a global variable in MATLAB

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.

Answers


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

Referring to your comment towards gnovice using a global variable can be an approach to solve your issue, but it's not a commonly used.

First of all make sure that your .m files are functions and not scripts. Scripts share a common workspace, making it easy to unwillingly overwrite your variables. In contrast, functions have their own scope.

Use xUnit in order to generate repeatable unit test for your functions. By testing each function involved in your program you will track down the error source. Having your unit test in place, further code modifications, can be easily verified.


A possible way to get around the global mess is to assign the variable as appdata. You can use the functions setappdata and getappdata to assign and retrieve appdata from a MATLAB window. As long as a MATLAB session is active there exists a window denoted by 0.

>> setappdata(0,'x',10)  % 0 indicates the root MATLAB window

Now the variable x is not visible to any script or function but can be accessed wherever needed by using getappdata.

function test
    globalX = getappdata(0,'x');
    disp(globalX);
end

x =
    10

The good news is that you can assign any valid MATLAB object to appdata, just be cautious with the names, using unique names for appdata fields like ModelOptimizerOptions instead of a generic x,y would help. This works on compiled executables and code deployed on the MATLAB production server as well.


Need Your Help

Spring-boot automatically import applicationContext.xml?

java spring spring-boot

I'm using spring-boot and would like to automatically import src/main/resources/applicationContext.xml file.

Is there a hook similar to Class#inherited that's triggered only after a Ruby class definition?

ruby class inheritance metaprogramming

#inherited is called right after the class Foo statement. I want something that'll run only after the end statement that closes the class declaration.