Resetting individual properties to default values: 2018b
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
D. Plotnick
am 11 Apr. 2019
Beantwortet: Steven Lord
am 14 Apr. 2019
Hello all, I am trying to figure out how to reset class properties of the following form:
classdef myClass
properties
A (:,1) double = ones(10,1)
B (:,:) double
C (:,:) double
end
methods
function obj = partialReset(obj)
obj.B = [];
obj.A = setAsDefault;
end
end
end
Here, I am trying to reset some of my class properties, but not all. 3 cases above
(A) I want to reset A to its default value (whatever I set it as)
(B) I want to set B to its default empty value
(C) I want to leave C as is.
Now, I can see some workarounds:
function obj = partialReset(obj)
objTmp = myClass;
obj.A = objTmp.A;
obj.B = objTmp.B;
end
This returns an error, oddly enough: 'Size of value must match specified dimensions M×1 or be scalar', so while the empty property is valid on construction, it is not on assignment? Alternatively:
function objReset = partialReset(obj)
objReset = myClass;
objReset.C = obj.C;
end
I could do it this way, but this seems overly complicated if I am only resetting a few properties, and I have a lot that are being preserved. Note too that:
function obj = partialReset(obj)
obj.B = []
end
returns the error 'Size of value must match specified dimensions.
So, my question is whether there is a simple way to reset individual properties to their default values in Matlab 2018b.
-Cheers,
DP
0 Kommentare
Akzeptierte Antwort
Steven Lord
am 14 Apr. 2019
The most straighforward way is probably to define a Hidden, Constant property holding the default value. Since it's Hidden it won't be visible to users of your class and because it's Constant you can use it to define the public property. Something like this should work.
classdef classWithDefaultValue
properties(Hidden, Constant)
defaultx = pi;
end
properties
x = classWithDefaultValue.defaultx;
end
methods
function obj = resetx(obj)
obj.x = obj.defaultx;
end
end
end
Use it like:
y = classWithDefaultValue
y.x = exp(1)
y = resetx(y)
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Software Development Tools finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!