Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB - Dependent properties and calculation

Tags:

oop

matlab

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

like image 397
Dang Khoa Avatar asked Nov 11 '11 19:11

Dang Khoa


People also ask

What are dependent properties in MATLAB?

Dependent properties do not store data. The value of a dependent property depends on some other value, such as the value of a nondependent property. Dependent properties must define get-access methods ( get. PropertyName ) to determine a value for the property when the property is queried.

What is a dependent property?

Dependent property means premises operated by others whom you depend on in any way for continua- tion of your normal business operations.

How do I set properties in MATLAB?

To assign a value to a property from within the class constructor, refer to the object that the constructor returns (the output variable obj ) and the property name using dot notation. When you assign a value to a property in the class constructor, MATLAB evaluates the assignment statement for each object you create.


1 Answers

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.

like image 82
Jonas Avatar answered Nov 15 '22 17:11

Jonas