外部インタフェース/API | ![]() ![]() |
複数の入出力を渡す
パラメータplhs[]
とprhs[]
は、各左辺(出力)変数と各右辺(入力)変数へのポインタを含むベクトルです。plhs[0]
は、1番目の左辺引数へのポインタを含み、plhs[1]
は2番目の左辺引数へのポインタを含みます。同様に、prhs[0]
は1番目の右辺引数へのポインタを含み、prhs[1]
は2番目の右辺引数へのポインタを含みます。
この例題xtimesy
では、入力スカラに対して、入力スカラまたは行列を乗算し、行列を出力します。たとえば、2つのスカラを与えてxtimesy
を使います。
x = 7; y = 7; z = xtimesy(x,y) z = 49
x = 9; y = ones(3); z = xtimesy(x,y) z = 9 9 9 9 9 9 9 9 9
#include "mex.h" /* * xtimesy.c - example found in API guide * * Multiplies an input scalar times an input matrix and outputs a * matrix. * * This is a MEX-file for MATLAB. * Copyright (c) 1984-2000 The MathWorks, Inc. */ /* $ Revision: 1.10 $ */ void xtimesy(double x, double *y, double *z, int m, int n) { int i,j,count=0; for (i=0; i<n; i++) { for (j=0; j<m; j++) { *(z+count) = x * *(y+count); count++; } } } /* The gateway routine */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *y,*z; double x; int status,mrows,ncols; /* Check for proper number of arguments. */ /* NOTE: You do not need an else statement when using mexErrMsgTxt within an if statement. It will never get to the else statement if mexErrMsgTxt is executed. (mexErrMsgTxt breaks you out of the MEX-file.) */ if(nrhs!=2) mexErrMsgTxt("Two inputs required."); if(nlhs!=1) mexErrMsgTxt("One output required."); /* Check to make sure the first input argument is a scalar. */ if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || mxGetN(prhs[0])*mxGetM(prhs[0])!=1 ) { mexErrMsgTxt("Input x must be a scalar."); } /* Get the scalar input x. */ x = mxGetScalar(prhs[0]); /* Create a pointer to the input matrix y. */ y = mxGetPr(prhs[1]); /* Get the dimensions of the matrix input y. */ mrows = mxGetM(prhs[1]); ncols = mxGetN(prhs[1]); /* Set the output pointer to the output matrix. */ plhs[0] = mxCreateDoubleMatrix(mrows,ncols, mxREAL); /* Create a C pointer to a copy of the output matrix. */ z = mxGetPr(plhs[0]); /* Call the C subroutine. */ xtimesy(x,y,z,mrows,ncols); }
この例題が示すように、複数の入出力を扱うMEX-ファイルゲートウェイの作成は簡単です。ベクトルprhs
とplhs
のどのインデックスが関数の入出力引数に対応するかを見るだけでいいのです。上記の例では、入力変数x
はprhs[0]
に対応し、入力変数y
はprhs[1]
に対応します。
mxGetScalar
はx
へのポインタではなくx
の値を出力することに注意してください。これは、スカラ操作のその他の方法です。x
を1行1列の行列として扱い、x
のポインタを出力するためにmxGetPr
を使います。
![]() | 文字列を渡す | 構造体とセル配列を渡す | ![]() |