Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 270
Amit Avatar asked Feb 06 '11 06:02

Amit


People also ask

How do you declare a global variable in MATLAB?

Create a function in your current working folder that returns the value of a global variable. These two functions have separate function workspaces, but they both can access the global variable. function r = getGlobalx global x r = x; Set the value of the global variable, x , and obtain it from a different workspace.

How do you declare a global variable?

The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.

How do you define a global variable in MATLAB GUI?

If 'global' means, that the variable needs to be shared between callbacks of a figure only, use either set/getappdata, guidata or the 'UserData' of the corrsponding GUI element. This allows e.g. to run two instances of the same GUI without conflicts. Please ask, if you need further explanations for this.


2 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 
like image 168
gnovice Avatar answered Sep 21 '22 18:09

gnovice


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.

like image 24
zellus Avatar answered Sep 19 '22 18:09

zellus