Dave_L
Dave_L

Reputation: 383

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

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?

Upvotes: 5

Views: 520

Answers (2)

Jonas
Jonas

Reputation: 74940

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

Upvotes: 9

Serg
Serg

Reputation: 14108

add to the class definition:

classdef testIt < handle

Upvotes: 0

Related Questions