How to fill mxArray with mxGetComplexDoubles?

9 ビュー (過去 30 日間)
Darrell Bircsak
Darrell Bircsak 2020 年 8 月 31 日
編集済み: James Tursa 2020 年 8 月 31 日
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!

採用された回答

James Tursa
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 件のコメント
Darrell Bircsak
Darrell Bircsak 2020 年 8 月 31 日
Thanks James! Well explained. Thanks for the example too!
James Tursa
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 ExchangeMATLAB Compiler についてさらに検索

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by