How to fill mxArray with mxGetComplexDoubles?

15 views (last 30 days)
Should this C code work?
int main() {
mxArray* array_ptr;
double start_real[6] = { 1.01, 2.02, 3.03, 4.04, 5.05, 6.06 };
double start_imag[6] = { 0.2, 0.3, 0.4, 0.5, 0.6, 0.7 };
array_ptr = mxCreateNumericMatrix(2, 3, mxSINGLE_CLASS, mxCOMPLEX);
#ifdef MX_HAS_INTERLEAVED_COMPLEX
mxComplexDouble* pc;
pc = mxGetComplexDoubles(array_ptr);
memcpy(&pc->real, start_real, 6 * sizeof(double));
memcpy(&pc->imag, start_real, 6 * sizeof(double));
#else
memcpy(mxGetPr(array_ptr), start_real, 6 * sizeof(double));
memcpy(mxGetPi(array_ptr), start_imag, 6 * sizeof(double));
#endif
return 0;
}
When I call mxGetComplexDoubles, the value returned is NULL! I think that is by design because the array is currently empty. However, how do I fill my array given the old way (with mxGetPr and mxGetPi) vs. the new way... whatever that new way is...?
I keep reading https://www.mathworks.com/help/matlab/matlab_external/upgrade-mex-files-to-use-interleaved-complex.html for help, but I don't understand why the call to mxGetComplexDoubles is NULL! Please help! Thanks!

Accepted Answer

James Tursa
James Tursa on 31 Aug 2020
Edited: James Tursa on 31 Aug 2020
No, this would not be expected to work. In the first place, you need to use mxDOUBLE_CLASS to create the mxArray, not mxSINGLE_CLASS. In the second place, for the interleaved complex model, you need to copy the data in a loop to get it into the interleaved memory. memcpy( ) can only be used to copy to/from contiguous memory, and your real and imaginary parts are not contiguous ... they are interleaved. E.g.,
#ifdef MX_HAS_INTERLEAVED_COMPLEX
double* pc;
int i;
pc = (double *) mxGetData(array_ptr);
for( i=0; i<6; i++ ) {
pc[2*i ] = start_real[i];
pc[2*i+1] = start_imag[i];
}
  2 Comments
Darrell Bircsak
Darrell Bircsak on 31 Aug 2020
Thanks James! Well explained. Thanks for the example too!
James Tursa
James Tursa on 31 Aug 2020
Edited: James Tursa on 31 Aug 2020
P.S. If you use a loop for both memory models (i.e., assign the elements directly), then the type doesn't have to match. I.e., you can use mxSINGLE_CLASS for the mxArray and things will still work as long as you type pc as a float* type. That's because the assignment will take care of the type conversion for you.

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB Compiler in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!