MATLAB Answers

How do I set a class property?

46 views (last 30 days)
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 Comments
Igor Arkhandeev
Igor Arkhandeev on 26 Jan 2021
I understand how to do this through the constructor. The thing is, I don't want to pass a variable to the input of a function every time. My code is complex and consists of a large number of nested functions. I want to avoid using global, so I need to pass my variable every time. This variable is only used in the class.

Sign in to comment.

Accepted Answer

per isakson
per isakson on 26 Jan 2021
Edited: per isakson on 26 Jan 2021
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 Comments
Igor Arkhandeev
Igor Arkhandeev on 26 Jan 2021
Okay, thank you so much for your response and for your time. I should have asked that. Now I should rebuild the code in a more convenient way.

Sign in to comment.

More Answers (1)

Steven Lord
Steven Lord on 26 Jan 2021
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.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!