MATLAB: How to fill mxArray with mxGetComplexDoubles

MATLABmxgetcomplexdoublesmxgetpi

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!

Best Answer

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];
}