Monday, May 30, 2011

Neat Coding Trick # 2

My Day of Coding last Friday turned up a really useful trick for passing data between Matlab and C/C++ during execution. Suppose you have some C++ code and lots of data, and you want to visualize or otherwise examine your data during runtime either to debug your code or just to make sure that things are happening the way you think they are. Matlab has provided tools to allow you to do just that: pass data from C/C++, during runtime, to Matlab. There, the data can be visualized or otherwise manipulated, and even sent back to C++. Not too bad.

The basic steps are:
  • include engine.h - this is an include file that automatically installs with Matlab
  • define an "engine" pointer, which opens up a portal between C++ and Matlab
  • define Matlab-friendly data elements (mxArrays) for porting your data to Matlab
  • stuff data into the Matlab-friendly data elements
  • instruct C++ to send the Matlab-friendly data elements to Matlab
  • instruct C++ what commands to execute on the data
There are of course more sophisticated options; see Matlab online documentation for more details.

I've put together a brief video outlining the technique. The code shown in the video can be downloaded from here: http://www.box.net/shared/xmazi14uv2

1 comment: