update instance property data without creating a new object?

How can I update a property without creating a new instance, using an instance method? For example:
classdef TestClass
properties
A = [];
end
methods
function obj=updateA(obj, val)
obj.A = val;
end
end
end
This will update A:
x = TestClass
x.A = 5;
However,
x.updateA(10)
will not update the instance x, but will create a new instance with the modified A. How can I update the property A of x using a class method without creating a new instance?

 채택된 답변

Adam
Adam 2017년 1월 16일
x = x.updateA(10)
will update the current object.
Or you can derive your class from 'handle' to make it a pass-by-reference class which does not need to re-assign obj, but beware this has other implications too.

댓글 수: 2

x = x.updateA(10) will work, but it's kinda ugly. I'll look into the handle option. Thanks!
Well, that's the way pass-by-value classes work, you always have to reassign to the object. It was not at all intuitive to me either when I first did it (and still now since I use mostly handle-derived classes) since I came from a C++ background rather than some other language where this concept is also explicit.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Argument Definitions에 대해 자세히 알아보기

태그

질문:

2017년 1월 16일

댓글:

2017년 1월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by