0

This is probably a very basic question, but I did not find anything on the internet. I am writing a matlab class, which has various class properties. I am setting all of them (some with input arguments, some default). I change one class variable in another class method. This does not work (the variable gets deleted when out of the function scope). What is the best way to solve this? Put everything in the constructor?

classdef MyClass
properties
    matrix1
    matrix2
    matrix3
end
methods
    function obj = MyClass()
    obj.matrix1 = zeros(2)
    obj.matrix2 = ones(3)
    end

    function obj = func(obj)
    obj.matrix2 = 3*ones(3)
    end
    function obj = func2(obj)
    obj.matrix3 = obj.matrix2 %this does not work. matrix2 has its original value, not 3*ones(3)
    end
end
end

I call it like

object = MyClass()
   object.func()
   object.func2()
kassio
  • 57
  • 1
  • 12
  • Show us your code - thats the best way to get help! – matlabgui Aug 15 '17 at 12:54
  • Checkout different between value class and handle class. https://stackoverflow.com/questions/26357059/why-isnt-this-matlab-class-holding-on-to-its-properties?rq=1 – Navan Aug 15 '17 at 13:08
  • Incidentally, you would get the expected results if you overwrite `object` with the return value for each call: `object = object.func(); object = object.func2();` This is how you have to use a **value class** (see linked questions for explanation). – gnovice Aug 15 '17 at 16:56

1 Answers1

1

MATLAB supports both value-type and reference-type classes.

The way you have defined your class, it is inherently a value type, which means that each function call uses a copy of your object, and does not refer to the calling object's data.

To make a class behave as a reference type, that would then modify the object's data as you require, inherit your class from handle.

Do:

classdef MyClass < handle
    % Everything else same here...
end
crazyGamer
  • 1,119
  • 9
  • 16