- Property Default Values, in particular the note there
- How matlab evaluates expressions , which tells you that because the expression x=X is evaluated outside of any workspace.
global variables used in members of class properties
14 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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.
0 Commenti
Risposta accettata
Guillaume
il 3 Dic 2018
Modificato: Guillaume
il 3 Dic 2018
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.
6 Commenti
Guillaume
il 4 Dic 2018
Really, the safest and simplest is to pass that initial to the constructor. Where you get that initial value is then completely independent of the class. You can use a global if you wish. Again,
classdef myclass
properties
x;
end
methods
function this = myclass(X) %constructor
this.x = X;
end
end
end
%your main program
global X;
%...
obj = myclass(X); %create object of myclass using global X
If you really want to embed the global in the class, then
classdef myclass
properties
x;
end
methods
function this = myclass
global X;
this.x = X;
end
end
end
I would really recommend that you use the first option.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Assembly in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!