C MEX ファイルでのスカラー値の受け渡し
行列としてのスカラーの受け渡し
この例では、スカラー値を渡す MEX ファイルを作成する方法を説明します。
次の C コード timestwo があるとします。これは、スカラー入力 (1 行 1 列の行列) を取り、それを倍にします。
void timestwo(double y[], double x[])
{
y[0] = 2.0*x[0];
return;
}C コードの解析
MEX ファイルとして作成された関数を表示するには、MATLAB® エディターで timestwo.c ファイルを開きます。
C/C++ では、コンパイラが関数の引数の個数と型をチェックします。しかし MATLAB では、任意の個数や任意の型の引数を関数に渡すことができ、関数が引数をチェックします。MEX ファイルでは可変の入力も可能です。MEX ファイルは、サポートされている任意の型の、任意数の入力引数や出力引数を安全に処理しなければなりません。
以下のコードは、引数の個数が適切かどうかをチェックします。
if(nrhs != 1) {
mexErrMsgIdAndTxt( "MATLAB:timestwo:invalidNumInputs",
"One input required.");
} else if(nlhs>1) {
mexErrMsgIdAndTxt( "MATLAB:timestwo:maxlhs",
"Too many output arguments.");
}
以下のコードは、入力が実数で double のスカラー値であるかどうかをチェックします。
mrows = mxGetM(prhs[0]);
ncols = mxGetN(prhs[0]);
if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) ||
!(mrows==1 && ncols==1) ) {
mexErrMsgIdAndTxt( "MATLAB:timestwo:inputNotRealScalarDouble",
"Input must be a noncomplex scalar double.");
}
例のビルドとテスト
MEX ファイルをビルドします。
mex -v -R2018a timestwo.c
関数を呼び出します。
x = 2; y = timestwo(x)
y =
4値によるスカラーの受け渡し
この例では、スカラーを値によって渡す MEX ファイルの作成方法を説明します。
関数 mxGetScalar は、スカラー変数 x のコピーを指すポインターではなく、スカラーの値を返します。
以下の C コードは、関数 timestwo_alt を実装します。
void timestwo_alt(double *y, double x)
{
*y = 2.0*x;
}timestwo_alt の関数シグネチャを timestwo の関数シグネチャと比較します。
void timestwo_alt(double *y, double x)
void timestwo(double y[], double x[])
入力値 x は double 型のスカラーです。関数 timestwo では、入力値は double 型の行列です。
MEX ファイルとして作成された関数を表示するには、MATLAB エディターで timestwoalt.c ファイルを開きます。
timestwo_alt の呼び出しを timestwo の呼び出しと比較します。
/* Get the scalar value of the input x */ /* note: mxGetScalar returns a value, not a pointer */ x = mxGetScalar(prhs[0]); /* Assign a pointer to the output */ y = mxGetDoubles(plhs[0]); /* Call the timestwo_alt subroutine */ timestwo_alt(y,x);
/* Assign pointers to each input and output. */ x = mxGetDoubles(prhs[0]); y = mxGetDoubles(plhs[0]); /* Call the timestwo subroutine. */ timestwo(y,x);
mxGetScalar が作成した値 x はスカラーであり、ポインターではありません。