How to modify properties of a Matlab Object [duplicate]
Asked Answered
S

2

26

I've created a MATLAB class, something like:

classdef myclass

  properties
      x_array = [];
  end

  methods
    function increment(obj,value)
       obj.x_array = [obj.x_array ; value);
    end
  end
end

The problem is, the property x_array is never modified when I invoke the increment() function: ex:

>>s = myclass
>>increment(s,5)

>>s.x_array
ans = []

I did some research, and I reached a conclusion that this is because of MATLAB using Lazy Copy for objects, making my class inherit the HANDLE class should have solved this, but it didn't, does anybody know why this is happening? And if extending the handle class is indeen the solution, isn't this the right way to do it:

classdef myclass < handle

or are there any extra steps?

Shaker answered 7/11, 2008 at 16:27 Comment(0)
C
27

This is similar to this question. In short all you should have to do is inherit from handle class.

Quick example

Contents of file myclass.m

classdef myclass<handle
    properties
        x_array = []
    end
    methods
        function obj=increment(obj,val)
            obj.x_array=[obj.x_array val];
        end
    end
end

Now from the Matlab command prompt, you can do the following

>> s=myclass;
>> s.increment(5)
>> s.increment(6)
>> s

s = 

myclass handle

properties:
    x_array: [5 6]

lists of methods, events, superclasses
Cass answered 7/11, 2008 at 17:46 Comment(1)
To make a comparison, the handle class constructor acts as a traditional python class?Ataraxia
H
0

There is an easier way. You only need to overwrite your initial instance s as follows:

s = increment(s,5);

More information in the documentation.

PS: While it is fine to use handle, the way copy function works is different and you should be careful about the way you use it. When you use handle, in fact you are making a new address/reference to an obj

Hegira answered 8/9, 2016 at 12:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.