Using pointers in Matlab

et3

Original blog illustration by Cali Rossi

Before we move back to Matlab, I am very happy to announce, for the new year, that Matlabtips.com got itself a professional illustrator. We are now well equipped to fulfill our mission : Make learning Matlab easy and entertaining. Among my resolutions for new year, there is one to make tons of new posts (illustrated this time with original drawings!).

As I discussed already several times, Matlab has supposedly no real equivalent to the C pointer available to you. This is so due to a design choice from Mathworks. The entire language is organized to avoid pointers. Even so, there are occasions where a pointer is really what we need, like when you are dealing with very large datasets that take nearly the entire memory. In this post, I first introduce you to the world of pointer and then shows you how to use them in Matlab for real.  

But first things first, what is a pointer (folks that know can jump a few lines here) ?

Well, as stated, a pointer points at. A pointer is the address of an object in memory. To explain why this is useful, let’s take a very recent topic : Christmas.

Let’s suppose you bought two gifts to your daughter. A small doll and a trampoline. It is very likely that you are going to give the doll directly to her while you will mention where the trampoline gift is (like : “take a look in the garden”). In other words, you will pass the doll “by value” (the object directly) and the trampoline by reference (where it is).  Already you see the advantage : You want to pass things “by reference” when it is too big to be transported around to be passed “by value”.

It’s all the same in programming languages. Some objects can take a very large space in memory and you don’t want this space to be duplicated. Indeed whenever you pass a variable to a function like :

function Parent()
   GIFT='Doll';
   GIFTback=giveDaughter(GIFT);
   GIFT
end

function receivedGIFT=giveDaughter(receivedGIFT)
 receivedGIFT=['dressed ',receivedGIFT];
end

When GIFT is passed to giveDaughter, it is passed by value. Then if it is modified within the function, a copy is made so that the original GIFT in the Parent function is not modified. If you run this example, you will see that GIFT stays ‘Doll’ even after its been modified in giveDaughter. The modified value is stored back in GIFTback.

If you want to avoid this behavior and modify directly the GIFT object in the Parent function, there are several ways.

To do this, you could use global variables. These are variables that are available everywhere in all functions like so :

function Parent()
global GIFT;
   GIFT='Doll';
   giveDaughter();
   GIFT
end

function giveDaughter()
global GIFT;
 GIFT=['dressed ',GIFT];
end

But the problem with global is that they are global!
Do you really want every single child in the world to have access to your big GIFT? Of course not, if it is really big, you want to pass it only to who it belongs to.

Another solution would be to use In place computation. But this mechanism is rather obscure and is absolutely not officially documented. Definitely not a nice way to hand a precious GIFT.

The best solution would be to use pointers but how in Matlab?

The answer lies in a tiny bit of Object Oriented Code. Indeed, as I posted already, handle objects are like pointer and luckily for us, Matlab allows you to create new class that inherits all of the properties of the handle class.

But don’t worry, this is very simple Object Oriented code. All you have to do is create a HandleObject.m M-file with this code :

classdef HandleObject < handle
   properties
      Object=[];
   end

   methods
      function obj=HandleObject(receivedObject)
         obj.Object=receivedObject;
      end
   end
end

Place this M-file in a folder where your code is (or under a path that is stored in your matlab paths) and you are ready to go.

I guess this will probably be your first OO code, so let’s explain a little bit what is going on.

classdef HandleObject < handle asks Matlab to create a new class that inherits its property from the handle class (a class of pointers!).

In this class, there is one single property (a property is more or less a variable associated to your object) called Object. The methods HandleObject is being called when you create the object with the argument ‘receivedObject’. This argument is stored in the property Object via the syntax obj.Object.

Now the equivalent of our previous code, using POINTERS would be :

function Parent()
   GIFT=HandleObject('Trampoline')
   giveDaughter(GIFT);
   GIFT.Object
end

function giveDaughter(receivedGIFT)
receivedGIFT.Object=['broken ',receivedGIFT.Object];
end

Please note how I use the ‘.’ to access the underlying object stored in the HandleObject. Also you see the usage of HandleObject(‘Trampoline’) to create (usually this is called the constructor of the class) the object using the first argument.

This time the original trampoline is broken in the Parent hands as well…

Did you know it was so easy to use pointers in Matlab?

Related Posts

This entry was posted in Advanced, Optimizing your code. Bookmark the permalink.

16 Responses to Using pointers in Matlab

  1. Matteo says:

    Ciao,
    innanzitutto complimenti per il sito :-)

    volevo solo avvertire che la funzione così come scritta non mi funziona (non so se per via della mia versione di matlab, R2010b, oppure per un errore).

    Io l’ho modificata così:

    % ————————————————————–
    classdef HandleObject < handle
    properties
    Object=[];
    end
    methods
    function obj = HandleObject(receivedObject)
    obj.Object = receivedObject;
    end
    end
    end
    % ————————————————————–

    Ciao ciao

  2. Paul says:

    I believe @Matteo is correct. For the block of code beginning

    classdef HandleObject

    line 07 must begin with

    function obj=

    Thanks.

  3. Just a silly typo in GIFT=['dressed ,GIFT]; An apostrophe after dressed is missing.

  4. S Gay says:

    Thanks but doesn’t work for me.

    x.a=1;
    y=HandleObject(x);
    y.Object.a=2;

    x.a (gives 1).

    An example of its application would be very useful.

    • Jerome says:

      In your particular example, when you pass x to HandleObject, it passes it by value.
      The pointer is y itself that stores the actual data in y.Object.

      x will stay independent of y.

      You should pass around y, not x, as y is your pointer.

  5. S Gay says:

    Please give the example of what to do

  6. S Gay says:

    I tried this:

    y=HandleObject(x)
    x.Object=2
    y.Object gives 2

    but:
    x.Object=1
    y.Object=2

    x.Object gives 1.

    This is potentially very confusing as it isn’t like c++ at all. I don’t know what it is, and I would suggest it should be avoided even though I appreciate your comments.

    • Jerome says:

      You misunderstood the purpose of this. y is not a pointer to x at all. It is a pointer to y.Object

      Let’s suppose you have a 10,000 by 10,000 matrix that takes huge amount of memory that you want to move around in multiple functions. You just create it within y.Object and pass around y.

  7. S Gay says:

    OK, thanks. In the initial posting :

    “As I discussed already several times, Matlab has supposedly no real equivalent to the C pointer available to you. ”

    This implied (to me) that we were going to emulate a C pointer. I obviously misunderstood.

    Hence it would have been clearer if:

    “As I discussed already several times, Matlab has no equivalent to the C pointer available to you. “

  8. hypermoi says:

    Great post :-)
    I think there is juste a small typo. It should be:
    function obj=HandleObject(receivedObject)

    instead of:
    function obj=HandleObject(obj,receivedObject)

  9. SK Mody says:

    A bit late in the day but thank you.

    I’d like to point out an issue though. Typically,
    one would use the handle as follows:

    thing = SomeThing();
    thing_handle = HandleObject(thing);
    thing_handle.Object.Modify();

    Now the moment the Modify() function tries to modify
    thing_handle.Object, a new copy of thing will be created
    due to copy-on-write. So this would always lead to at least
    one copy of the object being made. If the object is large
    then this could be inefficient.

    I don’t know if the matlab interpreter is smart enough not
    to make a copy if it determines that the original thing is never
    used after being passed to HandleObject. It would be
    safer to assume that the interpreter is not so smart and
    in that case, to get around this, one would need to write:

    thing = SomeThing();
    thing_handle = HandleObject(thing);
    clear thing;
    thing_handle.Object.Modify();

    But this is a little inconvenient, since you have to remember
    to clear thing every time. So instead one could write a
    ‘creator’ function:

    function h = CreateHandle(clsnm, varargin)
    hclsfun = str2func(clsnm);
    thing = hclsfun(varargin{:});
    h = HandleObject(thing);
    clear thing;
    end

    then you could write:
    thing_handle = CreateHandle(‘SomeThing’, ….contructor arguments…);
    thing_hande.Object.Modify();

    BTW, I like Yair Altman’s “Undocumented ..” blog, but it is a bit too
    Java oriented for me. I’ve not come across any another that delves
    a little bit into the inner workings of Matlab. So your blog is much
    needed. If its not asking too much, perhaps you could write something
    about the C/C++ interfaces to Matlab, which is where a lot of numerics
    people could benefit.

    Thanks again and good luck.

    • Jerome says:

      Thank you for a very detailed comment.

      Yes, a post on creating MEX files has been in my mind for some time, also on the deploy process. I am trying to alternate between higher level posts and more beginners posts. The list of things still to cover is long obviously but I am slowly writing my Matlab book-blog.

Leave a Reply