Thursday, March 31, 2011

Adventures with Visual Studio 2010 and Matlab

I had to write a C-Mex function to be called from a Matlab script. I first wrote the C-Mex interface, then the algorithm in a separate C file and added unit tests using Visual Studio 2010's C++. I spent a lot of time on not-so-intuitive details.

I wanted to pass a two dimensional array (DCM_ce) to a function (calcXYMinusHFromLLH). In the main body, the Visual Studio watch gave correct answers:

But when it entered the function, the watch value was wrong. I realized that when passing multidimensional arrays to a function in C, Visual Studio's watch gives wrong answers. If you use printf, you see the real value that is used:

My suffering did not end yet(!) Later on, when I called the C-Mex function from an m-file script, I noticed that the interface function (mexGetPr) took the transpose of the 2-D matrix. I had to re-transpose it so as to obtain the original input from my m-file:

When I finished the job, the time I spent was like this:
* Designing and documenting the algorithm: 0.5 days
* Converting the algorithm to C code (with all necessary helper functions): 0.5 days
* Wrestling with Visual Studio: 1 day
* Wrestling with C-mex: 1 day

As you see, environmental problems took most of my time. That's a good reason to have specialized folks for implementing algorithms, especially if the project is complex.

No comments: