Jeff Mather’s Dispatches

The 9 to 5 Life of an International Playboy

  • Home
  • A Miscellany of New England Iconography
  • Work Syllabus

Using C++ iterators on MATLAB mxArrays

Posted in August 15th, 2008
by Jeff Mather in C, MATLAB, Computing

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 {
  private:
    T      *v;
    mwSize thesize; 

  public:
    // 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())
    {
        count++;
    }

    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;
}

read more from this topic.....

No Comments

From the Yellow Notepad: C

Posted in May 27th, 2008
by Jeff Mather in From the Yellow Notepad, C, Software Engineering, Computing

Amazon.com - A Book on C Here are a few notes from the yellow notepad I’ve been using for school over the last six months. This first installment touches on C. Later I’ll add some UNIX programming and C++ notes. Basically these are the things that struck me as I was quickly reading the “refresher” material for my spring class: “Advanced C Programming for UNIX.” After more than a decade with C, I feel I know the core language pretty well; and here are the things that struck me as worth noting.

Is there a portable way to refer precisely to datatypes of a particular size? Yes, in C99 #include <stdint.h>.

Use signed integer types larger than char with getc() or getchar() to accomodate EOF (-1).

A good running average is avg += (x - avg) / n; It reduces the chance of overflow, is fast, and doesn’t require you to keep track of all values.

Each comment collapses to a single blank character during parsing.

Many system names start with an underscore ( “_” ). Avoid creating new identifiers that start that way.

All functions have extern storage, just like variables defined outside of a function.

Use volatile when it’s possible that the variable’s value will change from outside the normal flow of control. Technically this prevents compiler and processor instruction reordering optimizations around the use of the variable.

The register storage class is for small, fast-changing variables like loop indices (not for bigger things like arrays). And you can’t do &variable for register-declared storage.

Array names are const pointers, so an array name is not a valid l-value.

It’s not possible to take an address of a literal value, like 3.14 or “I am the very model of a modern major general.”. So . . .

Because C-strings are either arrays (char s[]) or pointers to memory areas (char *s), it’s illegal to reassign a value to a string variable directly (e.g., s = “new string”; /* won’t compile */).

When passing multidimensional arrays to a function, the function’s argument list must give the size of all but the slowest changing dimension.

Function pointers: int (*f)(int, double) is the same as int f(int, double). The parentheses are necessary to ensure the * binds to f and not int. To use the function pointer f either of these is acceptable: (*f)(37, 3.14) or f(37, 3.14). (This is “declaration follows usage.”)

const int *p is a pointer to a constant int.
int const *p is a constant pointer to an int.

“LP64″ scheme means long ints and pointers are 64-bit values.

Some compilers use precompiled headers to speed up compilation. This can make the inclusion order of header files significant. Also, some compilers (like Xcode) use “prefix headers,” which are always included in a project.

Defining NDEBUG turns the assert() macro into a no-op.

read more from this topic.....

No Comments

Recent Entries

  • Quickly Finding Numeric Patterns in MATLAB
  • Using C++ iterators on MATLAB mxArrays
  • What I did on my summer vacation (part 3)
  • What I did on my summer vacation (part 2)
  • What I did on my summer vacation (part 1?)
  • Coming Soon: What I Did on my Summer Vacation
  • My Spring of 100 Mistakes - Part 4
  • Tractors
  • Back on the air soon…
  • West of the Imagination

Recent Comments

  • ShaneBooth in My Spring of 100 Mistakes - Part 4
  • Leslie M-B in What I did on my summer vacation (p…
  • Jeff Mather in My Spring of 100 Mistakes - Part 4
  • mary in My Spring of 100 Mistakes - Part 4
  • mary in What I did on my summer vacation (p…
  • Jeff Mather in My Spring of 100 Mistakes - Part 4
  • Alex. in My Spring of 100 Mistakes - Part 4
  • Chris in My Spring of 100 Mistakes - Part 4
  • mary in Denver: Gateway to the West
  • mary in Blown Away

Social Network

  • Subscribes to feed
  • Stumble this site main post
  • Add to my Technorati favourite

Translators

French German version Spanish version Italian version

Categories

  • Always the bridesmaid
  • Baseball
  • Book Notes
  • Burying Grounds
  • C
  • Central Asia
  • Color and Vision
  • Commonwealth Project
  • Computing
  • Development
  • Europe
  • File Formats
  • Fodder for Techno-weenies
  • From the Yellow Notepad
  • General
  • High Tension
  • Historical Record
  • History
  • I like type
  • India
  • Large Format Camera
  • Life Lessons
  • MATLAB
  • OPP
  • Photography
  • Software Engineering
  • This is who we are
  • Travel
  • Uncategorized
  • USA
  • Worthy Feeds

Archives

  • September 2008
  • August 2008
  • July 2008
  • June 2008
  • May 2008
  • April 2008
  • March 2008
  • February 2008
  • January 2008
  • December 2007
  • November 2007
  • October 2007
  • September 2007
  • August 2007
  • July 2007
  • June 2007
  • May 2007
  • April 2007
  • March 2007
  • February 2007
  • January 2007
  • December 2006
  • November 2006
  • October 2006
  • September 2006
  • August 2006
  • July 2006
  • June 2006
  • May 2006
  • April 2006
  • March 2006
  • February 2006
  • January 2006
  • December 2005
  • November 2005
  • October 2005
  • September 2005
  • August 2005
  • July 2005
  • June 2005
  • May 2005

Pages

  • Home
  • A Miscellany of New England Iconography
  • Work Syllabus

Blogroll

Meta

  • Login
  • Valid XHTML
  • Valid CSS
  • WordPress
  • Theme Author
©2008 Jeff Mather’s Dispatches
Powered by WordPress | Talian designed by VA4Business, Virtual Assistance for Business who's blog can be found at Steve Arun's Virtual Marketing Blog