Resetting individual properties to default values: 2018b
조회 수: 8 (최근 30일)
이전 댓글 표시
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
채택된 답변
Steven Lord
2019년 4월 14일
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Software Development Tools에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!