Using C++ iterators on MATLAB mxArrays

Here’s a little something for the MATLAB lovers out there who also program in C++. The code sample at the end of this post shows how to add a C++ iterator to an mxArray, which is the basic datatype for MATLAB arrays. This makes it harder to walk off the end of an mxArray during linear traversal of all of the elements in an array and (hopefully) improves the readability of code that accesses the data stored inside mxArrays. The code gives a couple simple-minded examples of element-wise traversal (provided the MATLAB array you give it is a UINT8 array).

If you’re familiar with the C++ Standard Library, you can start to use your wrapped mxArray like an STL container. I use the term “like” advisedly, since it’s not actually a container. To reduce memory overhead, I don’t make a copy of the data that gets put into ArrayWrapper. Consequently, it doesn’t model the container concept that element lifetimes are the same as the “container” lifetime. You’re shouldn’t count on being able to use ArrayWrapper with any ole STL function. But then again, you might be able to use it with some; I haven’t tried.

#include "mex.h"
#include <cstddef>

// Treat an mxArray like a container.
// (See Josuttis. "The C++ Standard Library." 1999. p. 219-220)
template<class T>
class ArrayWrapper {
    T      *v;
    mwSize thesize;

    // Type definitions
    typedef T         value_type;
    typedef T*        iterator;
    typedef const T*  const_iterator;
    typedef T&        reference;
    typedef const T&  const_reference;
    typedef mwSize    size_type;
    typedef ptrdiff_t difference_type;

    // Constructor
    ArrayWrapper(const mxArray *theArray)
        v = static_cast<T*>(mxGetData(theArray));
        thesize = mxGetNumberOfElements(theArray);

    // Iterator support
    iterator begin() { return v; }
    const_iterator begin() const { return v; }
    iterator end() { return v + thesize; }
    const_iterator end() const { return v + thesize; }

    // Direct element access
    reference operator[](size_type i) { return v[i]; }
    const_reference operator[](size_type i) const { return v[i]; }

    // Size is constant
    size_type size() const { return thesize; }
    size_type max_size() const { return thesize; }

void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
    const mxArray *inputArray = prhs[0];

    ArrayWrapper<uint8_T> inData(inputArray);

    // 1- Count the number of samples in the image.
    mwSize count = 0;
    ArrayWrapper<uint8_T>::const_iterator i = inData.begin();
    while (i++ != inData.end())

    mexPrintf("The image has %ld samples.\n", count);

    // 2 - Halve the image values.
    mxArray *outputArray = mxDuplicateArray(prhs[0]);
    ArrayWrapper<uint8_T> outData(outputArray);

    i = inData.begin();
    ArrayWrapper<uint8_T>::iterator j = outData.begin();
    while (i != inData.end())
        *(j++) = *(i++) * 0.5;
    plhs[0] = outputArray;
This entry was posted in C, Computing, MATLAB. Bookmark the permalink.

2 Responses to Using C++ iterators on MATLAB mxArrays

  1. rogerroger says:

    Thanks, very useful.

  2. Peter says:

    Thanks very much! I took your work and extended it. I’m pretty new to STL so can’t be sure it’s really okay, but it seems to be working for my purposes (std::nth_element and std::max_element run on mxArray data).

    Here’s my extensions:

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>