1

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'?

chappjc
  • 30,359
  • 6
  • 75
  • 132
user1361521
  • 87
  • 1
  • 1
  • 4

1 Answers1

0

You can't. set always accepts only two arguments. You could work around it with an additional dependent property:

classdef test < handle

    properties
        a
        b
    end

    properties (Dependent = true)
        c
        d
    end

    methods
        function c = get.c(obj)
            c = obj.a + obj.b;
        end
        function d = get.d(obj)
            d = c;
        end

        function obj = set.c(obj, value)                
            obj.a = value - obj.b;
        end
        function obj = set.d(obj, value)                
            obj.b = value - obj.a;
        end

    end
end

or by choosing a different syntax and/or approach:

myObject.set_c(5,'a')  %// easiest; just use a function
myObject.c = {5, 'b'}  %// easy; error-checking will be the majority of the code
myObject.c('a') = 5    %// hard; override subsref/subsasgn; good luck with that

or something else creative :)

Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
  • you might be able to do this if you override subsref – janh Apr 12 '14 at 14:46
  • @janh: but you cannot use syntax like `myObject.c = 5`, you'd have to do something non-standard and perhaps unintuitive, like `myObject.c('a') = 5` – Rody Oldenhuis Apr 15 '14 at 07:12
  • afaik you can't override `set.c(obj)` Matlab doesn't allow it. you can however, and as you pointed out, override subsref to mimic `set.c(obj, value)`. and yes, you then still need something like `myObject.c = {5, 'b'}`. I use `myObject.set_c` to work around Matlab disallowing overriding a getter in a subclass. all that said, the objects need to be refactored ;) – janh Apr 15 '14 at 12:44