MATLAB: How to import C++ arrays into Matlab & loop over a C++ program from within Matlab

arrayscmex

I would like to know the particular steps I must take in order to connect Matlab and C++ for the following problems:
1. How can I import the results from a C++ program, in particular a 5-dim array of doubles and a 5-dim array of strings, into Matlab in order to analyse the results? 2. I would like to call a C++ program from within Matlab, handing over one parameter, letting the C++ program run and getting a resulting constant back. Depending on this resulting constant I want to change the input parameter and loop over the C++ program again. It shall result in kind of a golden section search…
I already had a look at the Matlab documentation and in particular the mex function. I managed to install the necessary compilers for mex and can compile the original C++ code. Additionally I tried out the arrayProduct_01.cpp. However, I got lost in the comprehensive documentation and am quite confused by now… What do I really need of all this and how to adjust it for my problem?
Thanks a lot for any help!!

Best Answer

Thanks for posting your code.
I haven't checked your indexing logic yet, but before we get into that you must first correct your pointer types. MATLAB stores char data as 2-bytes per char, not 1-byte per char as in C. Using a (char *) type in C to copy MATLAB char data is only going to get half of the data copied. So change all of your (char *) types in C that are used for MATLAB char array data to (mxChar *) instead, the macro defined in the API header files to deal with character elements (some type of 2-byte unsigned integer behind the scenes).
Regarding the indexing, I can't give specific advice without knowing more details of what you are doing. That being said, the general advice is that MATLAB stores arrays in memory in "column" order (like Fortran), but C/C++ store arrays in memory in "row" order. So if you are copying between them this needs to be accounted for. Either you need to explicitly write the code for element-by-element copying or use a combination of memcpy and permute functionality. E.g., for a 2 x 3 case:
MATLAB:
x = zeros(2,3);
The storage order in memory will be:
x(1,1)
x(2,1)
x(1,2)
x(2,2)
x(1,3)
x(2,3)
In C/C++:
double x[2][3];
The storage order in memory will be:
x[0][0]
x[0][1]
x[0][2]
x[1][0]
x[1][1]
x[1][2]
Even after accounting for the 1-based vs 0-based indexing, you can see that the indexing in memory doesn't match up between the two. If you needed to copy the C/C++ array to MATLAB, one method would be to create a 3 x 2 mxArray (i.e., dimensions reversed), then use memcpy on the entire block of memory, and then on the MATLAB side transpose it. That would get you back to the ordering you would expect. For multi-dimensional arrays, e.g. 3 x 4 x 5 in C/C++, create the mxArray as 5 x 4 x 3, then use memcpy on the entire block, then on the MATLAB side permute(array,[3 2 1]).