Attaching function to Matlab struct

27 views Asked by At

Is it possible to attach a function to a class property of type struct? Intended usage:

% Definition:
classdef a < handle
  properties
    bar
  end
  methods
    function obj = a()
      obj.bar = struct;
      %obj.bar.attachFunction('apply', @someFunction); <-- something like this
    end
  end
end

% Usage:
foo = a();
foo.bar.apply('test');
foo.bar.var1 = 1;
foo.bar.var2 = 2;
1

There are 1 answers

1
casparjespersen On

Oh well, that was actually quite simply once I used my mind.

classdef a < handle
  properties
    bar
  end
  methods
    function obj = a()
      obj.bar = struct;
      obj.bar.apply = @(str) @obj.barApply(str);
    end
  end
  methods (Access=protected)
    function barApply(obj, str)
      obj.bar.something = str;
    end
  end
end

foo = a();
foo.bar.apply('monkey');
foo.bar.apple = 2;