scmg
scmg

Reputation: 1894

matlab class - method allows user choosing which property to be modified

i want to build a class like that:

classdef myclass < handle
  properties
    v1 = struct('value', 100)
    v2 = struct('value', 200);
  end
  methods
    function plusone(obj, vars)      % SHOULD BE MODIFIED SOMEHOW??
      vars.value = vars.value + 1;
    end
  end
end

And my question is, how should i write the method plusone so in Command Window i can choose which property i want to modify, i.e. i choose to modify property v2:

a = myclass();
a.plusone(a.v2);

that update the field value of variable v2 of object a ? Or is there a problem with my thinking method?

Upvotes: 1

Views: 43

Answers (1)

Jonas
Jonas

Reputation: 74930

Yes, you can create a method like that, though you need to pass the reference to the field differently:

methods
    function plusone(obj, propName)      
      obj.(propName).value = obj.(propName).value + 1;
    end
end

To call the method, pass the reference as string:

a = myclass();
a.plusone('v2')

Upvotes: 1

Related Questions