Search code examples
matlabmatlab-class

How to change the property of an instance in Matlab


I'm new to MATLAB, and I want to write a method of a class that change the property of this object:

classdef Foo

  properties
    a = 6;
  end
  methods
    function obj = Foo()
    end

    function change(obj,bar)
      obj.a = bar
    end
  end
end




foo = Foo()

foo.change(7) //here I am trying to change the property to 7

It turns out the property is still 6.


Solution

  • MATLAB makes a difference between value classes and handle classes. Instances of value classes are implicitely copied on assignments (and hence behave like ordinary MATLAB matrices), instances of handle classes are not (and hence behave like instances in other OOP languages).

    Therefore, you have to return the modified object for value classes:

    classdef ValueClass
        properties
            a = 6;
        end
        methods
            function this = change(this, v)
                this.a = v;
            end
       end
    end
    

    Call it like this:

    value = ValueClass();
    value = value.change(23);
    value.a
    

    Alternatively, you can derive your class from the handle class:

    classdef HandleClass < handle
        properties
            a = 6;
        end
        methods
            function change(this, v)
                this.a = v;
            end
       end
    end
    

    And call it like this:

    h = HandleClass();
    h.change(23);
    h.a
    

    There's more information in the MATLAB documentation.