Suppose I have the following class:
classdef myClass
properties
Globals = struct(...
'G1', 1, ...
'G2', 2 ...
);
end
methods
% methods go here
end
end
I use the struct because there are other properties that are structs.
Is there any way to provide a setter for a field of the struct? Naively providing
function obj = set.Globals.G1(obj, val)
obj.Globals.G1 = val; % for example
end
doesn't work.
You have to define the set-method for the entire struct (see below). Alternatively, you can define a class for "Globals", which will look and feel like a structure for most practical purposes (except that you can't misspell field names), and which can implement its own set/get methods for its properties.
function obj = set.Globals(obj,val)
%# look up the previous value
oldVal = obj.Globals;
%# loop through fields to check what has changed
fields = fieldnames(oldVal);
for fn = fields(:)' %'#
%# turn cell into string for convenience
field2check = fn{1};
if isfield(val,field2check)
switch field2check
case 'G1'
%# do something about G1 here
case 'G2'
%# do something about G2 here
otherwise
%# simply assign the fields you don't care about
obj.Globals.(field2check) = val.(field2check);
end
end
end
end %# function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With