MATLAB: Global variables used in members of class properties

classglobaloop

classdef myclass
properties
x=X
end
methods
end
end
X is a global variable. I want x to start with a default value of X. Later x will change. What should I do to claim that X is a global variable? I know by using a function in methods, one can construct myclass with a start value of x assigned as a global variable (X putting in this function), but I wonder if there's a way of not using a function.

Best Answer

Global variables are usually indication of bad design. Avoid them as much as possible.
In your case, using a global variable to initialise the default property of a class would be an extremely bad idea, fraught with peril. If you're not aware of when and how default values are actually computed, abandon that idea immediately.
When you write:
classdef myclass
properties
x = X;
end
end
X is evaluated only once, when the class is first loaded in memory. If you were to change the global X after that, your default value would stay the same (unless you clear classes). If X has yet to be created when the class is loaded in memory (which may be well before you actually use it), you will get an obscure error as well.
Essential reading:
Saying all that, if you're hell bent on a bad design:
classdef myclass
properties
x = getGlobalX; %Don't go there, you may be eaten by a grue
end
end
%local function
function x = getGlobalX
global X;
x = X;
end
may work, although I haven't actually tested.
edit: Perhaps I should have asked: why are you coming up with this design? There's probably a much better way of achieving whatever you're trying to do which doesn't involve global.