複数の異なる数値配列を含む構造体を MEX 関数に渡し、そのフィ​ールドにアクセスさせ​るにはどうすればよい​ですか?

4 次查看(过去 30 天)
MATLAB では、数値配列を要素に持つ構造体を使用し、その配列をMEX 関数に渡すことで、そのすべてのフィールドにアクセスできるようにしています。
数値配列を含む構造体を MEX 関数に渡し、そのフィールドにアクセスさせるにはどうすればよいですか?

采纳的回答

MathWorks Support Team
このワークフローは、MEX-API 関数の 'mxIsStruct' で mxArray が構造体かどうかを、 'mxGetNumberOfFields' で mxArray が構造体を表す場合のフィールド数を、 'mxGetFieldNameByNumber' で構造体を表す mxArray のフィールド名を、取得することにより実現されます。
この他、mxGetFieldByNumber' は構造体を表す mxArray の特定のフィールドの構造体配列の特定の要素の内容を取得し、 'mxGetNumberOfElements' は mxArray が持つ要素数を取得します。
サンプルプログラムは以下の通りです。
/*\n * structArrays.c\n *\n * This is a MEX file for MATLAB.\n*/\n\n#include "mex.h"\n#include "matrix.h"\n\n/* The gateway function */\nvoid mexFunction(int nlhs, mxArray *plhs[],\n int nrhs, const mxArray *prhs[])\n{\n /* Print out the number of input arguments to the MEX-function */\n mexPrintf("Number of input arguments %d\n", nrhs);\n\n /* loop over all the input arguments to the MEX-function */\n for (mwSize iEl = 0; iEl < nrhs; ++iEl) {\n /* Get the mxArray corresponding to the current input */\n const mxArray* my_el = prhs[iEl];\n \n /* Check if the mxArray is a struct */\n bool isStruct = mxIsStruct(my_el);\n if (isStruct) {\n /* Get the number of fields */\n int numFields = mxGetNumberOfFields(my_el);\n mexPrintf("Number of fields %d\n", numFields);\n\n /* loop over all number of fields*/\n for (mwSize iFields = 0; iFields < numFields; ++iFields) {\n const char* namefield = mxGetFieldNameByNumber(my_el, iFields);\n mexPrintf("Field name: %s\n", namefield);\n\n /* Get mex-array */\n const mxArray *my_arr = mxGetFieldByNumber(my_el, 0, iFields);\n\n /* Check if mex-array represents a double field */\n bool isDouble = mxIsDouble(my_arr);\n if (isDouble) {\n mwSize numEl = mxGetNumberOfElements(my_arr);\n mxDouble *Value = mxGetDoubles(my_arr);\n for (mwSize i = 0; i < numEl; ++i)\n mexPrintf("%f ", Value[i]);\n mexPrintf("\n\n");\n }\n }\n\n }\n \n }\n}
上記のソースコードを以下でコンパイルします。
>> mex structArrays.c -R2018a
ここで、API 関数 'mxGetDoubles' を使用するため、フラグ '-R2018a' が必要です。詳細については以下をご覧ください。
MATLAB 上では以下のようにして実行します。
ここで、'structArrays' は MEX ファイル名です。ここでは次のような出力を得ることができます。
>> my_struct.arr1 = [1 2; 3 4];\nmy_struct.arr2 = [1 2 3; 4 5 6];\nmy_struct.arr3 = [1 2 3; 4 5 6; 7 8 9];\n>> structArrays(my_struct)\nNumber of input arguments 1\nNumber of fields 3\nField name: arr1\n1.000000 3.000000 2.000000 4.000000 \n\nField name: arr2\n1.000000 4.000000 2.000000 5.000000 3.000000 6.000000 \n\nField name: arr3\n1.000000 4.000000 7.000000 2.000000 5.000000 8.000000 3.000000 6.000000 9.000000

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 C MEX ファイル アプリケーション 的更多信息

标签

尚未输入任何标签。

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!