Azzera filtri
Azzera filtri

Why I cannot change the class property in this case?

17 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

Matt J
Matt J il 16 Gen 2023
Modificato: Matt J il 16 Gen 2023
You called setpos() without returning anything. So, you need to have,
myobject1 = myobject1.setpos([100, 0, 0])
  2 Commenti
NoYeah
NoYeah il 17 Gen 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 il 17 Gen 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.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Construct and Work with Object Arrays in Help Center e File Exchange

Prodotti


Release

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by