【问题标题】:MATLAB - Dependent properties and calculationMATLAB - 相关属性和计算
【发布时间】:2011-12-27 06:56:16
【问题描述】:

假设我有以下类计算二次方程的解:

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

现在假设我运行以下命令:

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

此时,quadcalc.x = [-2 -2]。假设我多次调用quadcalc.x 而不调整其他属性,即每次我请求此属性时都调用quadcalc.x = [-2 -2]quadcalc.x 重新计算每次,还是只是“记住”[-2 -2]?

【问题讨论】:

    标签: oop matlab


    【解决方案1】:

    是的,x 每次都会重新计算。这就是拥有依赖属性的意义所在,因为它保证x 中的结果始终是最新的。

    如果您想让x 成为“惰性依赖属性”,您可能需要查看我对this question 的回答中的建议。

    【讨论】:

    • 假设我在其他依赖属性中使用了xx 也会为所有其他从属属性重新计算,是吗?
    猜你喜欢
    • 1970-01-01
    • 2015-01-22
    • 2016-10-03
    • 1970-01-01
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 2018-07-23
    相关资源
    最近更新 更多