Using pointers in Matlab


Original blog illustration by Benedicte Rossi

Before we move back to Matlab, I am very happy to announce, for the new year, that 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()

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

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;

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

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

      function obj=HandleObject(receivedObject)

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()

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

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?

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

23 Responses to Using pointers in Matlab

  1. Matteo says:

    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
    function obj = HandleObject(receivedObject)
    obj.Object = receivedObject;
    % ————————————————————–

    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=


  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 (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.Object gives 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);

    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;

    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;

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

    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.

  10. Scott says:

    I wish this worked for the intended use, but it seems to me that matlab objects don’t deal well with large objects in matlab. Every time data is set on or retrieved from an object, a deep copy is made. So if you’re using the class for large data, your access times will be quite slow.

    • jerome says:

      Can you be more specific when this happen? I haven’t had this problem yet. So your experience could be very interesting

      • Nico says:

        I observe the same behavior than Scott, with Matlab R2016b.
        Here my code:

        A = randn(6000);
        B = HandleMatrix(6000, 6000, ”); = randn(6000);
        tic; A = test1(A); toc
        tic; C = test1(A); toc
        tic; test2(B); toc

        function X = test1(X)
        X = X+1;

        function test2(X) = + 1;

        The Matlab response:
        Elapsed time is 0.034098 seconds
        Elapsed time is 0.066533 seconds
        Elapsed time is 0.104615 seconds

        The HandleMatrix class:
        classdef HandleMatrix < handle

        function obj = HandleMatrix(x,y,type)
        if strcmp(type, 'single'),y) = single(0);
        else,y) = 0;

        • Nico says:

          There is a mistake in the code above, of course it’s “ = randn(6000);” instead of “C”…

  11. bkbirge says:

    Thanks for this, works great, now I can sling a 100mb custom database around with ease in Matlab R2011.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.