How do I set a class property?
9 次查看(过去 30 天)
显示 更早的评论
Good afternoon! I'm bad at object-oriented and I need some advice. The situation is as follows: in one part of the code, I calculate the integer variable var. Then I want this variable to be declared as the default property in the class. For example,
var = a * b;
...
classdef vector
properties
v = var;
end
methods
%%
end
end
How can I implement this?
4 个评论
Mario Malic
2021-1-26
Hey Igor,
See this video on YouTube for the brief introduction on OOP:
Object-Oriented Programming in MATLAB | Master Class with Loren Shure
From my slim knowledge of OOP, you can write the constructor method to create a class with desired value for your variable.
采纳的回答
per isakson
2021-1-26
编辑:per isakson
2021-1-26
This might help as a start
>> vec = vector;
>> vec.v1
ans =
120
>>
where
classdef vector
properties
v1 = var1_calculation;
v2 = vector.var2_calculation;
end
methods ( Static = true )
function var = var2_calculation()
a = -10;
b = 12;
var = a*b;
end
end
end
and
function var = var1_calculation()
a = 10;
b = 12;
var = a*b;
end
Then the question is where do a and b come from
4 个评论
per isakson
2021-1-26
I assume that a*b represents some larger costly calculation.
AFAIK: Matlab doesn't offer any better solution than the one in my answer (possibly I misunderstood your question).
The rhs of the assignments in the property block must be possible to evaluate in the base workspace. Both functions and static methods fullfill that requirement.
When vector is called for the first time the default value is calculated and the value is stored together with the class in memory. Doc says: "Evaluation of property default values occurs only when the value is first needed, and only once when MATLAB first initializes the class. MATLAB does not reevaluate the expression each time you create an instance of the class."
更多回答(1 个)
Steven Lord
2021-1-26
If you want to initialize the value once and have that be unchangeable for the rest of the lifetime of the object, make it a Constant property.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!