I am currently importing the real and imaginary parts of a matrix separately from Matlab to C++. I then also map the real and imaginary parts to Eigen separately. I also perform the calculation and map the final result separately, as shown below:
//import real and imaginary parts from matlab
mwSize M = mxGetM (prhs[1]);
mwSize N = mxGetN (prhs[1]);
double * PR = mxGetPr (prhs[1]);
double * PI = mxGetPi (prhs[1]);
//map real and imaginary parts to Eigen
Map<Matrix<double,Dynamic,Dynamic,ColMajor> > Br (PR, M, N );
Map<Matrix<double,Dynamic,Dynamic,ColMajor> > Bi (PI, M, N );
//map real and imaginary parts of result
plhs[0] = mxCreateDoubleMatrix(M, N, mxCOMPLEX);
Map<Matrix<double,Dynamic,Dynamic,ColMajor> > resultr (mxGetPr(plhs[0]), M, N);
Map<Matrix<double,Dynamic,Dynamic,ColMajor> > resulti (mxGetPi(plhs[0]), M, N);
//calculate real and imaginary parts of A*B separately
resultr=A*Br;
resulti=A*Bi;
However, as of R2018a, Matlab allows importing the real and imaginary parts together.
How can I do this? I tried the following:
//import complex matrix from matlab
mwSize N = mxGetN (prhs[1]);
mxComplexDouble * PR = mxGetComplexDoubles (prhs[1]);
//map complex matrix to eigen
Map<Matrix<mxComplexDouble,Dynamic,Dynamic,ColMajor> > B (PR, M, N );
//map complex result
plhs[0] = mxCreateDoubleMatrix(M, N, mxCOMPLEX);
Map<Matrix<mxComplexDouble,Dynamic,Dynamic,ColMajor> > result (mxGetDoubles(plhs[0]), M, N);
//calculate real and imaginary parts together
result=A*B;
But it does not compile because Eigen does not like the mxComplexDouble type.
If I understood correctly, mxComplexDouble
has the same layout as std::complex<double>
, so you should be able to simply cast:
auto* PR = reinterpret_cast<std::complex<double>*>(mxGetComplexDoubles(prhs[1]));
Reference:
In the
-R2018a
API, themxGetElementSize
function returnssizeof(std::complex<T>)
for a complexmxArray
with data typeT
. This value is twice the value returned by the function in the-R2017b
API.
From MATLAB documentation page "Upgrade MEX Files to Use Interleaved Complex API"