user1361521
user1361521

Reputation: 87

Matlab property that automatically updates

Being new to MATLAB, I am trying to write a class where, if one of two properties changes value, a third property is automatically recalculated.

It seems events and listeners are made for this, but I just can't get the hang of their basic implementation.

My latest attempt is this

% when property a or b is altered, c will automatically be recalculated

classdef myclass < handle
    properties
        a = 1;
        b = 2;
        c
    end

    events
        valuechange
    end

    methods

        function obj = myclass()
            addlistener(obj,'valuechange', obj.calc_c(obj))
        end

        function set_a(obj, input)
            obj.a = input;
            notify(obj, valuechange)
        end

        function set_b(obj, input)
            obj.b = input;
            notify(obj, valuechange)

        end

        function calc_c(obj)
            obj.c = obj.a + obj.b
        end
    end
end

Which returns following error

Error using myclass/calc_c
Too many output arguments.
Error in myclass (line 18)
            addlistener(obj,'valuechange', obj.calc_c(obj)) 

What am I doing wrong?

Upvotes: 1

Views: 187

Answers (1)

Alessandro L.
Alessandro L.

Reputation: 405

Don't you want instead to define c as Dependent, so that every time you use it you are sure that it has been updated?

Something like this

classdef myclass < handle
    properties
        a
        b
    end
    properties (Dependent) 
        c
    end

    methods
    function x = get.x(obj)
        %Do something to get sure x is consistent
        x = a + b;
    end
end

Upvotes: 1

Related Questions