1

I am trying to copy a boost::multi_array of std::complex values to an mxArray so I can write the values out to MATLAB .mat file. When I load the .mat file into MATLAB, it only has the real portions of the data and none of the imaginary portions. Here is a code snippet showing what I am doing.

boost::multi_array<std::complex<double>, 3> SAP_max_combined_complex(boost::extents[1][1][1], boost::fortran_storage_order());

// Later in the code
SAP_max_combined_complex.resize(boost::extents[xDim][yDim][zDim]);
// The multi_array is populated correctly - this has been verified

mwSize numDims = SAP_max_combined_complex.num_dimensions();
mwSize outputSizes[3] = {SAP_max_combined_complex.shape()[0], SAP_max_combined_complex.shape()[1], SAP_max_combined_complex.shape()[2]};
mxArray* outputData = mxCreateNumericArray(numDims, outputSizes, mxDOUBLE_CLASS, mxCOMPLEX);
memcpy(mxGetData(outputData), (void*) SAP_max_combined_complex.data(), (sizeof(std::complex<double>) * SAP_max_combined_complex.num_elements()));

// I then write the mxArray to the file with
matPutVariable(mpMatFile, fieldName.toStdString().c_str(), outputData);

Also of interesting note is if when I make the memcpy call, the deallocation of SAP_max_combined_complex crashes when I terminate my application. If I comment out the memcpy call, the deallocation works properly (or at least doesn't crash).

Any ideas what I am doing wrong? Thanks!

1 Answer 1

1

Matlab stores the real and imaginary part as separate arrays. mxGetData() only returns the pointer to the real part!

Your approach on the other hand (mainly because of std::complex), stores real and imaginary part as pairs.

You need to untangle the pairs of real and imaginary parts and write them in separate arrays (real part goes to mxGetData() and imag part to mxGetImagData()).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I did not realize they had different pointers. Now to find the optimal way to handle this. Discovered for whatever reason that calling memcpy is modifying the contents of my multi_array as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.