I have defined a list of private properties in MATLAB App Designer which are initialized as follows:
properties (Access = private)
prop1 = val1;
prop2 = val2;
...
end
I would now like to have a function that resets them to the default values as defined above. Is there an way to do this automatically or do I have to reset them manually (which can lead to errors eg when more properties are added)?
Also, is there a way to loop over all the properties I've defined in this way?
If you want to blanket reset only the private properties, you can use metaclass
to access the attributes of your properties and adjust as necessary.
For example:
classdef SOcode < handle
properties
a
b
end
properties (Access = private)
c = -1
d = -1
end
methods
function self = SOcode()
end
function changeprivate(self)
self.c = randi(5);
self.d = randi(5);
end
function printprivate(self)
fprintf('c = %d\nd = %d\n', self.c, self.d)
end
function resetprivate(self)
tmp = metaclass(self);
props = tmp.PropertyList;
nprops = numel(props);
for ii = 1:nprops
if strcmp(props(ii).SetAccess, 'private')
self.(props(ii).Name) = props(ii).DefaultValue;
end
end
end
end
end
Provides the desired behavior:
>> test = SOcode;
>> test.changeprivate;
>> test.printprivate;
c = 1
d = 1
>> test.resetprivate;
>> test.printprivate;
c = -1
d = -1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.