Effacer les filtres
Effacer les filtres

Why I cannot change the class property in this case?

18 vues (au cours des 30 derniers jours)
NoYeah
NoYeah le 16 Jan 2023
Commenté : Walter Roberson le 17 Jan 2023
Below is the example code of OBJECTO.m
classdef OBJECTO
properties (Access = private)
pos {mustbevector}
end
methods (Access = public)
function obj = OBJECTO(vec)
% constructor
if nargin < 1
obj.pos = [0, 0, 0];
else
obj.pos = vec
end
end
function obj = setpos(vec)
% set position
obj.pos = vec
end
function vec = getpos(obj)
% get position
vec = obj.pos
disp(vec)
end
end
end
and I made .m file to execute above. (remove ; for the debugging)
function ans = myfunc()
myobject1 = OBJECTO()
myobject1.setpos([100, 0, 0])
tmp = getpos(myobject1)
end
and in consol, typed the above function
myfunc()
the result says
ans =
OBJECTO with properties
pos = [0, 0, 0]
ans =
OBJECTO with properties
pos = [100, 0, 0]
tmp =
0 0 0
that means the instance of OBJECTO (I mean 'myobject1' in the above) value is not changened
I have changed the property pos from 'private' to 'public' but same thing occured
why this happens?

Réponse acceptée

Matt J
Matt J le 16 Jan 2023
Modifié(e) : Matt J le 16 Jan 2023
You called setpos() without returning anything. So, you need to have,
myobject1 = myobject1.setpos([100, 0, 0])
  2 commentaires
NoYeah
NoYeah le 17 Jan 2023
so if I want to modify some properties of a class, then I have to write handler twice?
Why the matlab choose the most uncomfortable way
Walter Roberson
Walter Roberson le 17 Jan 2023
Why would you write the handler twice?
MATLAB has two types of classes: value objects, and handle objects.
Value objects work like typical MATLAB numeric arrays, where operations on the object do not change the object unless you assign the new value over top of old one. Just like
A = 3;
update_me(A)
A
A = 3
function update_me(X)
X = X + 1;
end
This does not change the value of A and most people would not expect it to update the value of A.
Handle objects are more like passing around pointers to heap objects, where changes inside the class methods do change everyone's view of the object.
You should implement which-ever of the two makes sense in your situation. You do not need to implement both.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Construct and Work with Object Arrays dans Help Center et File Exchange

Produits


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by