How to fill mxArray with mxGetComplexDoubles?
6 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
采纳的回答
James Tursa
2020-8-31
编辑:James Tursa
2020-8-31
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 个评论
James Tursa
2020-8-31
编辑:James Tursa
2020-8-31
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 C Shared Library Integration 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!