0

If I have a MATLAB class MyClass with a

classdef MyClass 

    properties
        myArray
    end

    methods

        function update(obj, i)
            obj.myArray[i] = i*5;
        end
end

and I call the update function with

myClass.update(i)

the myArray object does not 'remember' the updates when i increments and I get left with an empty property. Ie. myArray = []

However if I define the function as follows

classdef MyClass 

    properties
        myArray
    end

    methods

        function out = update(obj, i)
            out = i*5;
        end
end

and call the update function with

myClass.myArray[i] = update(i)

the updates to the myArray property are remembered. Ie. Ie. myArray = [5, 10, 15, 20, 25]

So what is going on here?...in every other language this would work as expected, it seems like there is some MATLAB specific weird scoping/referencing going on here. Anybody know what's happening?

sonicboom
  • 4,928
  • 10
  • 42
  • 60

1 Answers1

4
classdef MyClass 

This defines a value class. Think of value classes as immutable: a member function of a value class should return a new instance of the value class.

You want a handle class, which is declared using the syntax

classsdef MyClass < handle

See here for more info.

rlbond
  • 65,341
  • 56
  • 178
  • 228