MATLAB - Dependent properties and calculation

2020-07-07 07:41发布

问题:

Suppose I have the following class which calculates the solution to the quadratic equation:

classdef MyClass < handle
    properties
        a
        b
        c
    end
    properties (Dependent = true)
        x
    end

    methods
        function x = get.x(obj)
            discriminant = sqrt(obj.b^2 - 4*obj.a*obj.c);
            x(1) = (-obj.b + discriminant)/(2*obj.a);
            x(2) = (-obj.b - discriminant)/(2*obj.a);
        end
    end
end

Now suppose I run the following commands:

>>quadcalc = MyClass;
>>quadcalc.a = 1;
>>quadcalc.b = 4;
>>quadcalc.c = 4; 

At this point, quadcalc.x = [-2 -2]. Suppose I call quadcalc.x multiple times without adjusting the other properties, i.e., quadcalc.x = [-2 -2] every single time I ask for this property. Is quadcalc.x recalculated every single time, or will it just "remember" [-2 -2]?

回答1:

Yes, x is recalculated every single time. This is kind of the point of having a dependent property, since it guarantees that the result in x is always up to date.

If you want to make x a "lazy dependent property", you may want to look at the suggestions in my answer to this question.



标签: oop matlab