MATLAB Answers

Resetting individual properties to default values: 2018b

조회 수: 18(최근 30일)
D. Plotnick
D. Plotnick 11 Apr 2019
답변: Steven Lord 14 Apr 2019
Hello all, I am trying to figure out how to reset class properties of the following form:
classdef myClass
A (:,1) double = ones(10,1)
B (:,:) double
C (:,:) double
function obj = partialReset(obj)
obj.B = [];
obj.A = setAsDefault;
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;
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;
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 = []
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.

채택된 답변

Steven Lord
Steven Lord 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;
x = classWithDefaultValue.defaultx;
function obj = resetx(obj)
obj.x = obj.defaultx;
Use it like:
y = classWithDefaultValue
y.x = exp(1)
y = resetx(y)

추가 답변(0개)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by