Declaring a global variable in MATLAB

后端 未结 3 822
暗喜
暗喜 2020-11-28 13:29

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 fi

相关标签:
3条回答
  • 2020-11-28 13:41

    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.

    0 讨论(0)
  • 2020-11-28 13:42

    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
    
    0 讨论(0)
  • 2020-11-28 14:03

    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.

    0 讨论(0)
提交回复
热议问题