OOP in MatLab -- assigning values to properties?

3 views (last 30 days)
I am trying to understand how MatLab does OOP in R2013b, so I got started with a simple test class, but it doesn't seem to behave as desired. The test class has 2 properties, A and B, which I keep at default scope (which I believe is public). I used the following class definition, with default values:
classdef classtest
properties
A = 0;
B = uint64(5);
end
methods
function changeA(obj, newA)
obj.A = newA;
end
function changeB(obj, newB)
obj.B = newB;
end
end
end
Then I run the following code, with outputs shown:
>> a=classtest;
>> a
a =
classtest with properties:
A: 0
B: 5
>> a.changeA(128);
>> a.changeB(256);
>> a
a =
classtest with properties:
A: 0
B: 5
>>
The values of A and B have not updated based on the method executed, but are instead still their default values.
What am I doing wrong?

Accepted Answer

Sean de Wolski
Sean de Wolski on 16 Oct 2013
Edited: Sean de Wolski on 16 Oct 2013
Your class is not a handle class but rather a value class. Thus when you run:
a.changeB(256);
A new variable ans in your workspace will exist with the change. If you want to update the value in this a and keep it as a value class, assign the output back to a:
a = changeA(a,128)
Or change your class to a handle class. It really depends on what you plan to do with this class as to whether you want it as a handle or value class:
classdef classtest < handle
  3 Comments
Daniel Shub
Daniel Shub on 16 Oct 2013
For the OP's definition of changeA, a = changeA(a,128) gives an error. It is worth pointing out that the handle/value class issue is flagged by mlint.
@Sam As for value and handle classes, I think the polynomial class example in the documentation highlights a good use case of a value class.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!