基于C/C++语言的一般MEX文件的内容如下:
#include "mex.h"
/*
*注释部分
*This is a MEX-file for MATLAB
*/
/*The gateway function 入口函数*/
void mexFunction(int nlhs,mxArray *plhs[],
int nrhs,const mxArray *prhs[])
{
/*variable declarations here 变量声明*/
/*code here */
}
从上面的程序中可以明显地看到,这个文件是一个典型的C语言文件,其程序语法完全满足标准C语言的语法要求。然而,其在结构上却有独特之处。
- 头文件的包含语句。所有的源文件中必须包含mex.h,该头文件完成了所有C语言MEX函数的原型声明,还包含了matrix.h文件,即对mx函数和数据类型的声明与定义。
- C语言MEX源文件的入口函数部分void mexFunction(int nlhs,mxArray *plhs[],int nrhs,xonst mxArray *prhs[])。这是MEX文件的必需部分,并且书写形式固定:括号;里的4个变量分别表示输出参数的个数,输出参数,输入参数的个数和输入参数。
程序中,输入/输出参数的类型均为mxArray,或者可以用中文称为“阵列”。阵列是MATLAB唯一能处理的对象;在C语言程序变形的MEX文件中,MATLAB阵列用结构体mxArray定义。
void arrayProduct(double x,double *y,double *z,int n)
{
int i;
for(i=0;i<n;i++){
z[i]=x*y[i];
}
}
上面是使用C/C++语言编程实现的方法,下面介绍使用MEX文件实现上述功能的方法。使用MATLAB通过调用MEX文件实现上述功能的步骤包括:
- 定义宏。
- 创建MEX源文件计算程序。
- 创建入口函数程序。
- 检查输入参数和输出参数。
- 读取输入数据。
- 准备输出数据。
- 进行计算。
- 编译链接生成MEX二进制文件。
- 测试MEX文件。
具体命令及其实现步骤如下:
/*1. Use Macro 使用宏包括头文件*/
#include "mex.h"
/*2. The computational routine 计算程序*/
void arrayProduct(double x,double *y,double *z,int n)
{
int i;
for(i=0;i<n;i++){
z[i]=x*y[i];
}
}
void mexFunction(int nlhs,mxArray *plhs,int nrhs,
const mxArray *prhs[])
{
double multiplier;
double *inMatrix;
size_t ncols;
double *outMatrix;
/* check for proper number of arguments 检查参数*/
if (nrhs!=2){
mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nrhs","Two inputs required.");
}
if (nlhs!=1){
mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nlhs","One outputs required.");
}
/*4. make sure the first input argument is a scalar 确定第一个参数为标量*/
if (!mxIsDouble(prhs[0])||mxIsComplex(prhs[0])||
mxGetNumberofElements(prhs[0])!=1) {
mexErrMsgIdAndTxt("MyToolbox:arrayProduct:notScalar","Input multiplier must be a scalar.");
}
/*5. get the value of the scalar input 获取参数*/
multiplier=mxGetScalar(prhs[0]);
/* create a pointer to the real data in the input matrix */
inMatrix=mxGetPr(prhs[1]);
/* get dimensions of the input matrix */
ncols=mxGetN(prhs[1]);
/* create the output matrix */
plhs[0]=mexCreateDoubleMatrix(1,(mwSize)ncols,mxREAL);
/* get a pointer to the real data in the output matrix */
outMatrix=mxGetPr(plhs[0]);
/* 6. call the computational routine */
arrayProduct(multiplier,inMatrix,outMatrix,(mwSize)ncols);
}