Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB - set/get access on fields of a struct?

Tags:

oop

matlab

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.

like image 706
Dang Khoa Avatar asked Oct 10 '22 06:10

Dang Khoa


1 Answers

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
like image 101
Jonas Avatar answered Oct 14 '22 04:10

Jonas