setting object properties in matlab classes

Hi there, I have a very simple question. Is it not possible in matlab to modify an objects properties in a function? I am seeing strange results, but I am sure I am doing something wrong. below is a simple class. I multiply the property value "prop" by 2 inside the function addEntry, but it doesnt reflect in the object once it exits the function. Can anyone help?
classdef dummyclass
properties
prop
end
methods
function obj = dummyclass()
obj.prop=1;
end
function flag = addEntry(obj)
obj.prop=obj.prop*2;
obj.prop
flag = 1;
end
end
end
q=dummyclass;
q.prop
q.addEntry()
q.prop

Respuestas (1)

Walter Roberson
Walter Roberson el 29 de Sept. de 2011
Unless you are using an object derived from the handle class, a copy of the object is modified. You have to return the modified object and store that over the original object.
function [obj, flag] = addEntry(obj)
obj.prop=obj.prop*2;
obj.prop
flag = 1;
end
and in user code,
[MyObj, flag] = MyObj.addEntry();

2 comentarios

ABAK
ABAK el 29 de Sept. de 2011
Thanks, that makes sense.
instead of doing what you are suggesting, can you point me in the right direction on setting this up correctly? i.e. creating a handle class and deriving from it? Its quite lame to create copies unnecessarily
Walter Roberson
Walter Roberson el 29 de Sept. de 2011
http://www.mathworks.com/help/techdoc/matlab_oop/brfylq3.html

Iniciar sesión para comentar.

Categorías

Más información sobre Creating, Deleting, and Querying Graphics Objects en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 29 de Sept. de 2011

Community Treasure Hunt

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

Start Hunting!

Translated by