Calling setter with a third argument?

3 views (last 30 days)
markushatg
markushatg on 3 Oct 2012
In a class with the dependent property c, I would like to call c's setter with a third argument that equals 'a' or 'b', choosing which independent property to alter in order to set c.
the code is
classdef test < handle
properties
a
b
end
properties (Dependent = true)
c
end
methods
function c = get.c(obj)
c = obj.a + obj.b;
end
function obj = set.c(obj, value, varargin)
if(nargin == 2)
obj.a = value - obj.b;
end
if(nargin == 3 && argin(3) == 'a') % how do I enter this loop?
obj.a = value - obj.b;
end
if(nargin == 3 && argin(3) == 'b') % or this?
obj.b = value - obj.a;
end
end
end
end
This call works:
myobject.c = 5
But how do i call the setter with a third parameter equaling 'a' or 'b'?
Thanks

Answers (1)

Daniel Shub
Daniel Shub on 3 Oct 2012
You can't. The set function can only take two arguments. You cannot change the function footprint. Even if you could change the function footprint, how would you call the set function?
You can cheat in three ways
The first is to call the set function with a cell array (or a structure ...)
myobject.c = {5, 'a'}
and then check if the input is a 2-element cell with one value equal to 'a' or 'b'. This of course assumes that you never actually want to set c to be {5, 'a'}. I would say that this is not a good solution.
The second would be to define a mysetc method identical to your set.c method and let this method do the setting. If you go this route you want to make the SetAccess for c to be private. This method means users need multiple interfaces for setting properties.
The third method builds on the second method. Define a set method.
function set(obj, property, value, varargin)
that parses the property to determine which set.x method to call. this means users would always use set(obj, prop, value). You could overload subsassgn to handle simple cases like myobj.c = 5
Note that the syntax for argin(3) is usually varargin{3}. Also handle class set methods do not return a value, but object class methods do.

Categories

Find more on Data Type Identification in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!