0

Possible Duplicate:
How do properties work in Object Oriented MATLAB?

I have been using MatLab for quite some time but started using OOP just recently.

I have a class that is a simple linked list (it can be anything really). A few methods are declared in the class. Is it possible for the methods to modify the instance from which those are called?

instance.plotData() cannot modify any properties of the instance .

I have to return the instance for the function to actually have some effect on the instance itself:

instance = instance.plotData();

This seems really cumbersome. Is there a better way of achieving the task?

Addition:

classdef handleTest < handle

  properties
      number
  end

  methods
      function addNode(this)
          a = length(this);
          this(a+1) = handleTest;
      end
  end
end

If i call:

x = handleTest
x.addNode()

then x has still only one node.

Community
  • 1
  • 1
user02222022
  • 165
  • 8

1 Answers1

1

A possible solution is to derive from the handle class, i.e. use something like

classdef YourClass < handle
    function plotData(obj)
        ... modify the obj here ...
    end
end

However, this also has implications, if you copy the instance, i.e. if you do an

a = YourClass(...);
b = a;

then b is an alias for a and whenever you change a, you also modify b and vice versa (meaning the data is only stored once in the background).

There is the Matlab documentation for handle classes and the difference to value classes.

Mehrwolf
  • 8,208
  • 2
  • 26
  • 38
  • Thanks, Mehrwolf. Is it possible to add instances of class to an already defined instance that is controlled with such a handle? For example, I have a "node" class. n(1) = node(); is the initialization line of the class instance. I would like to add more nodes to the vector -- a function would then execute the following command: n(2) = node(); and then modify the parameters of the node. The Handle version does not seem to work. Am I misrepresenting the handle operator? Thanks, SunnyBuy – user02222022 Aug 29 '12 at 16:50
  • @SunnyBoyNY: Could you ask this as a new question and post a short code example of your `node`? I think, I do not get completely, what you try to do. – Mehrwolf Aug 29 '12 at 17:08
  • let me edit the question – user02222022 Aug 29 '12 at 21:52
  • @SunnyBoyNY: Ok, no I get the point. I would not try to add the handle to itself (inside the class) but instead create a vector of `handleTest`, which is stored somewhere in your calling program. If you want to wrap this vector, you could create another class e.g. `handleList`. This class has an `addNode()` that adds an instance of `handleTest` to the internal vector. – Mehrwolf Aug 30 '12 at 06:50