Side effects of calling a MATLAB class instance don't persist
Asked Answered
K

2

5

If I make the following toy class in MATLAB:

classdef testIt
    properties
        a
        b
        c
    end
    methods
        function obj = testIt
            obj.a = 1;
            obj.b = 2;
        end

        function obj = set.a(obj,a)
            obj.a = a;
        end

        function obj = set.b(obj,b)
            obj.b = b;
        end

        function obj = addup(obj)
            obj.c = obj.a + obj.b;
        end
    end
end

and then instantiate and call the addup method:

>> aTest = testIt

Properties:
a: 1
b: 2
c: []

>> aTest.addup

Properties:
a: 1
b: 2
c: 3

>> aTest

Properties:
a: 1
b: 2
c: []

The property c has not been created. Instead, I need to use the syntax:

>> aTest = aTest.addup

>> aTest

Properties:
a: 1
b: 2
c: 3

Can anyone explain to me why this is necessary?

Kopje answered 13/12, 2012 at 20:3 Comment(1)
kinda duplicate of this, but @Jonas' answer is much nicer than the answers there :oNapper
E
9

Matlab supports two types of classes: handle classes, and value classes.

Value classes operate similar to structures and other Matlab variables, in that they are passed by value. Thus, if you want to modify an instance of a value class within a function, you need to return and overwrite the instance in the calling workspace.

Handle classes, on the other hand, are passed by reference. If you change the value of a property anywhere, the class is updated in all workspaces. For example, you can have a reference to the object in the base workspace, and one inside a GUI, and if you modify one, the other changes its value accordingly.

If you change your code to classdef testIt < handle, the objects will behave exactly the way you expect.

Also: Have a look at the documentation

Evetta answered 13/12, 2012 at 20:12 Comment(0)
T
0

add to the class definition:

classdef testIt < handle
Treadway answered 13/12, 2012 at 20:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.