Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 601
Dave_L Avatar asked Feb 18 '23 04:02

Dave_L


1 Answers

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

like image 76
Jonas Avatar answered Mar 04 '23 13:03

Jonas