外部インタフェース/API | ![]() ![]() |
C MEX-ファイルからの関数の呼び出し
API関数mexCallMATLAB
を使って、Cソースコード内からMATLAB関数、演算子、M-ファイル、その他のMEX-ファイルを呼び出すことができます。つぎの例は、mxArray
を作成し、サブ関数に様々なポインタを渡してデータを取得し、mexCallMATLAB
を呼び出して正弦関数を計算し、結果をプロットします。
/* $ Revision: 1.4 $ */ /*============================================================= * sincall.c * * Example for illustrating how to use mexCallMATLAB * * Creates an mxArray and passes its associated pointers (in * this demo, only pointer to its real part, pointer to number of * rows, pointer to number of columns) to subfunction fill() to * get data filled up, then calls mexCallMATLAB to calculate sin * function and plot the result. * * This is a MEX-file for MATLAB. * Copyright (c) 1984-2000 The MathWorks, Inc. *============================================================*/ #include "mex.h" #define MAX 1000 /* Subroutine for filling up data */ void fill( double *pr, int *pm, int *pn, int max ) { int i; /* You can fill up to max elements, so (*pr)<=max. */ *pm = max/2; *pn = 1; for (i=0; i < (*pm); i++) pr[i]=i*(4*3.14159/max); } /* Gateway function */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { int m, n, max=MAX; mxArray *rhs[1], *lhs[1]; rhs[0] = mxCreateDoubleMatrix(max, 1, mxREAL); /* Pass the pointers and let fill() fill up data. */ fill(mxGetPr(rhs[0]), &m, &n, MAX); mxSetM(rhs[0], m); mxSetN(rhs[0], n); /* Get the sin wave and plot it. */ mexCallMATLAB(1, lhs, 1, rhs, "sin"); mexCallMATLAB(0, NULL, 1, lhs, "plot"); /* Clean up allocated memory. */ mxDestroyArray(rhs[0]); mxDestroyArray(lhs[0]); return; }
sincall
つぎの例は、2つの変数を出力し、それらのうちの1つだけに値を割り当てるM-ファイルを作成します。
function [a,b]=foo[c]
a=2*c;
MATLABは、以下のワーニングメッセージを表示します。
Warning: One or more output arguments not assigned during call
to 'foo'.mexCallMATLAB
を使ってfoo
を呼び出す場合、割り当てられていない出力変数は、タイプmxUNKNOWN_CLASSです。
![]() | スパース配列の総さ | アドバンスドトピックス | ![]() |