matlab混合编程之mex文件
1:mex文件结构
a 子程序
b 入口程序
void mexFunction(int nlhs, mxArray *plhs[],int nrhs,const mxArray *prhs[]) { /*用户特定的代码….*/ }
2:语法
#include "mex.h" void timestwo_alt(double *y, double x) { *y = 2.0*x; } void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { double *y; double x; /* 检查参数 */ if (nrhs != 1) { mexErrMsgTxt("One input argument required."); } else if (nlhs > 1) { mexErrMsgTxt("Too many output arguments."); } else if (!mxIsNumeric(prhs[0])) { mexErrMsgTxt("Argument must be numeric."); } else if (mxGetNumberOfElements(prhs[0]) != 1 || mxIsComplex(prhs[0])) { mexErrMsgTxt("Argument must be non-complex scalar."); } /* 为输出参数创建变量 */ plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL); /* 为参数 x、y赋值,x为值,而y为指针 (由于MATLAB没有值传递,所以用指针才能得到修改后的y值, 不然修改的是y的一个副本,为临时变量,在函数返回时,y值没有变化, 不能得到希望的结果) */ x = mxGetScalar(prhs[0]); y = mxGetPr(plhs[0]); /* 调用timestwo_alt 子函数 */ timestwo_alt(y,x); }
3: 编译
编译链接C语言的MEX文件源程序,在MATLAB的控制窗口中输入:mex timestwoalt.c生成一个名为timestwoalt.mexw32的MEX文件
4:运行
x=2;
y=timestwoalt(x)
输出:y=4