MATLAB-相关属性和计算 [英] MATLAB - Dependent properties and calculation
问题描述
假设我有以下用于计算二次方程解的类:
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;
这时是quadcalc.x = [-2 -2]
.假设我多次调用quadcalc.x
而不调整其他属性,即每次我请求此属性时都quadcalc.x = [-2 -2]
.是每次都重新计算quadcalc.x
,还是只是记住" [-2 -2]?
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]?
推荐答案
是的,x
每次都会重新计算.之所以要具有从属属性,是因为它可以保证x
中的结果始终是最新的.
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.
如果要将x
设置为惰性依赖属性",则可能需要查看我对这个问题.
If you want to make x
a "lazy dependent property", you may want to look at the suggestions in my answer to this question.
这篇关于MATLAB-相关属性和计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!