- #include "mex.h"
- void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
- {
- mexPrintf("hello,world!\n");
- }
假设你把hello.c放在了C:\TEST\下,在Matlab里用CD C:\TEST\ 将当前目录改为C:\TEST\(注意,仅将C:\TEST\加入搜索路径是没有用的)。现在敲:
mex hello.c
如果一切顺利,编译应该在出现编译器提示信息后正常退出。如果你已将C:\TEST\加入了搜索路径,现在键入hello,程序会在屏幕上打出一行: hello,world!
nlhs:输出参数数目
plhs:指向输出参数的指针
nrhs:输入参数数目
例如,使用
[a,b]=test(c,d,e)
调用mex函数test时,传给test的这三个参数分别是 prhs[0]=c ,prhs[1]=d ,prhs[2]=e
当函数返回时,将会把你放在plhs[0],plhs[1]里的地址赋给a和b,达到返回数据的目的。
细心的你也许已经注意到,prhs[i]和plhs[i]都是指向类型mxArray类型数据的指针。 这个类型是在mex.h中定义的,事实上,在Matlab里大多数数据都是以这种类型存在。当然还有其他的数据类型,可以参考Apiguide.pdf里的介绍。
- //hello.c 2.0
- #include "mex.h"
- void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
- {
- int i;
- i=mxGetScalar(prhs[0]);
- if(i==1)
- mexPrintf("hello,world!\n");
- else
- mexPrintf("大家好!\n");
- }
将这个程序编译通过后,执行hello(1),屏幕上会打出:
hello,world!
而hello(0)将会得到:
大家好!
现在,程序hello已经可以根据输入参数来给出相应的屏幕输出。在这个程序里,除了用到了屏幕输出函数mexPrintf(用法跟c里的printf函数几乎完全一样)外,还用到了一个函数:mxGetScalar,调用方式如下:
i=mxGetScalar(prhs[0]);
"Scalar"就是标量的意思。在Matlab里数据都是以数组的形式存在的,mxGetScalar的作用就是把通过prhs[0]传递进来的mxArray类型的指针指向的数据(标量)赋给C程序里的变量。这个变量本来应该是double类型的,通过强制类型转换赋给了整形变量i。既然有标量,显然还应该有矢量,否则矩阵就没法传了。看下面的程序:
- //hello.c 2.1
- #include "mex.h"
- void mexFunction(int nlhs, mxArray *plhs[],
- int nrhs, const mxArray *prhs[])
- {
- int *i;
- i=mxGetPr(prhs[0]); //prhs是一个指针数组(每一个是一个指针),所以返回一个指针
- if(i[0]==1)
- mexPrintf("hello,world!\n");
- else
- mexPrintf("大家好!\n");
- }
这样,就通过mxGetPr函数从指向mxArray类型数据的prhs[0]获得了指向double类型的指针。
但是,还有个问题,如果输入的不是单个的数据,而是向量或矩阵,那该怎么处理呢 ?通过mxGetPr只能得到指向这个矩阵的指针,如果我们不知道这个矩阵的确切大小,就 没法对它进行计算。
为了解决这个问题,Matlab提供了两个函数mxGetM和mxGetN来获得传进来参数的行数 和列数。下面例程的功能很简单,就是获得输入的矩阵,把它在屏幕上显示出来:
- //show.c 1.0
- #include "mex.h"
- #include "mex.h"
- void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
- {
- double *data;
- int M,N;
- int i,j;
- data=mxGetPr(prhs[0]); //获得指向矩阵的指针
- M=mxGetM(prhs[0]); //获得矩阵的行数
- N=mxGetN(prhs[0]); //获得矩阵的列数
- for(i=0;i<M;i++)
- { for(j=0;j<N;j++)
- mexPrintf("%4.3f ",data[j*M+i]);
- mexPrintf("\n");
- }
- }
编译完成后,用下面的命令测试一下:
- a=1:10;
- b=[a;a+1];
- show(a)
- show(b)
- // 获取维度个数
- numOfDim = mxGetNumberOfDimensions(pArray);
- // 获取维度数组
- Dims = mxGetDimensions(pArray);
需要注意的是,在Matlab里,矩阵第一行是从1开始的,而在C语言中,第一行的序数为零,Matlab里的矩阵元素b(i,j)在传递到C中的一维数组data后对应于data[j*M+i] 。 输入数据是在函数调用之前已经在Matlab里申请了内存的,由于mex函数与Matlab共用同一个地址空间,因而在prhs[]里传递指针就可以达到参数传递的目的。但是,输出参数却需要在mex函数内申请到内存空间,才能将指针放在plhs[]中传递出去。由于返回指针类型必须是mxArray,所以Matlab专门提供了一个函数:mxCreateDoubleMatrix来实现内存的申请,函数原型如下:
mxArray *mxCreateDoubleMatrix(int m, int n, mxComplexity ComplexFlag)
m:待申请矩阵的行数
n:待申请矩阵的列数
为矩阵申请内存后,得到的是mxArray类型的指针,就可以放在plhs[]里传递回去了。但是对这个新矩阵的处理,却要在函数内完成,这时就需要用到前面介绍的mxGetPr。使用 mxGetPr获得指向这个矩阵中数据区的指针(double类型)后,就可以对这个矩阵进行各种操作和运算了。下面的程序是在上面的show.c的基础上稍作改变得到的,功能是将输出处理后的元素:
- //reverse.c 1.0
- #include "mex.h"
- void mexFunction(int nlhs, mxArray *plhs[],
- int nrhs, const mxArray *prhs[])
- {
- double *inData;
- double *outData;
- int M,N;
- int i,j;
- inData=mxGetPr(prhs[0]);
- M=mxGetM(prhs[0]);
- N=mxGetN(prhs[0]);
- plhs[0]=mxCreateDoubleMatrix(M,N,mxREAL);
- outData=mxGetPr(plhs[0]);
- for(i=0;i<M;i++)
- for(j=0;j<N;j++)
- outData[j*M+i]=inData[(N-1-j)*M+i];
- }
当然,Matlab里使用到的并不是只有double类型这一种矩阵,还有字符串类型、稀疏矩阵、结构类型矩阵等等,并提供了相应的处理函数。本文用到编制mex程序中最经常遇到的一些函数,其余的详细情况清参考Apiref.pdf。
通过前面两部分的介绍,大家对参数的输入和输出方法应该有了基本的了解。具备了这些知识,就能够满足一般的编程需要了。但这些程序还有些小的缺陷,以前面介绍的re由于前面的例程中没有对输入、输出参数的数目及类型进行检查,导致程序的容错性很差,以下程序则容错性较好
- #include "mex.h"
- void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
- {
- double *inData;
- double *outData;
- int M,N;
- //异常处理
- //异常处理
- if(nrhs!=1)
- mexErrMsgTxt("USAGE: b=reverse(a)\n");
- if(!mxIsDouble(prhs[0]))
- mexErrMsgTxt("the Input Matrix must be double!\n");
- inData=mxGetPr(prhs[0]);
- M=mxGetM(prhs[0]);
- N=mxGetN(prhs[0]);
- plhs[0]=mxCreateDoubleMatrix(M,N,mxREAL);
- outData=mxGetPr(plhs[0]);
- for(i=0;i<M;i++)
- for(j=0;j<N;j++)
- outData[j*M+i]=inData[(N-1-j)*M+i];
- }
在上面的异常处理中,使用了两个新的函数:mexErrMsgTxt和mxIsDouble。MexErrMsgTxt在给出出错提示的同时退出当前程序的运行。MxIsDouble则用于判断mxArray中的数据是否double类型。当然Matlab还提供了许多用于判断其他数据类型的函数,这里不加详述。
需要说明的是,Matlab提供的API中,函数前缀有mex-和mx-两种。带mx-前缀的大多是对mxArray数据进行操作的函数,如mxIsDouble,mxCreateDoubleMatrix等等。而带mx前缀的则大多是与Matlab环境进行交互的函数,如mexPrintf,mxErrMsgTxt等等。了解了这一点,对在Apiref.pdf中查找所需的函数很有帮助。
MX Matrix Library
Type for index values | |
Pointer type for platform | |
Signed integer type for size values | |
Type for size values | |
Field to structure array | |
Type for MATLAB array | |
Convert array to string | |
Check assertion value for debugging purposes | |
Check assertion value without printing assertion text | |
Offset from first element to desired element | |
Allocate dynamic memory for array using MATLAB memory manager | |
Type for string array | |
Enumerated value identifying class of array | |
Identifier corresponding to class | |
Flag specifying whether array has imaginary components | |
CHARACTER values from Fortran array to pointer array | |
COMPLEX*16 values from Fortran array to pointer array | |
COMPLEX*8 values from Fortran array to pointer array | |
INTEGER*1 values from Fortran array to pointer array | |
INTEGER*2 values from Fortran array to pointer array | |
INTEGER*4 values from Fortran array to pointer array | |
CHARACTER values from pointer array to Fortran array | |
COMPLEX*16 values from pointer array to Fortran array | |
COMPLEX*8 values from pointer array to Fortran array | |
INTEGER*1 values from pointer array to Fortran array | |
INTEGER*2 values from pointer array to Fortran array | |
INTEGER*4 values from pointer array to Fortran array | |
Pointer values from pointer array to Fortran array | |
REAL*4 values from pointer array to Fortran array | |
REAL*8 values from pointer array to Fortran array | |
REAL*4 values from Fortran array to pointer array | |
REAL*8 values from Fortran array to pointer array | |
Unpopulated N-D cell array | |
Unpopulated 2-D cell array | |
Unpopulated N-D string array | |
Create populated 2-D string array | |
2-D, double-precision, floating-point array initialized to 0 | |
Scalar, double-precision array initialized to specified value | |
N-D logical array initialized to false | |
2-D, logical array initialized to false | |
Scalar, logical array | |
Unpopulated N-D numeric array | |
Numeric matrix initialized to 0 | |
2-D unpopulated sparse array | |
Unpopulated 2-D, sparse, logical array | |
Create 1-by-N array initialized to specified string | |
Unpopulated N-D structure array | |
Unpopulated 2-D structure array | |
Free dynamic memory allocated by MXCREATE* functions | |
Make deep copy of array | |
Free dynamic memory allocated by MXCALLOC, MXMALLOC, or MXREALLOC functions | |
Contents of array cell | |
Pointer to character array data | |
Class of array | |
Class of array as string | |
Pointer to real data | |
Pointer to dimensions array | |
Number of bytes required to store each data element | |
Value of EPS | |
Field value, given field name and index, into structure array | |
Field value, given field number and index, into structure array | |
Field name, given field number, in structure array | |
Field number, given field name, in structure array | |
Pointer to imaginary data of array | |
Value of infinity | |
Sparse matrix IR array | |
Sparse matrix JC array | |
Pointer to logical array data | |
Number of rows in array | |
Number of columns in array | |
Value of NaN (Not-a-Number) | |
Number of dimensions in array | |
Number of elements in array | |
Number of fields in structure array | |
Number of elements in IR, PR, and PI arrays | |
Imaginary data elements in array of type DOUBLE | |
Real data elements in array of type DOUBLE | |
Value of public property of MATLAB object | |
Real component of first data element in array | |
String array to C-style string | |
Determine whether input is cell array | |
Determine whether input is string array | |
Determine whether array is member of specified class | |
Determine whether data is complex | |
Determine whether mxArray represents data as double-precision, floating-point numbers | |
Determine whether array is empty | |
Determine whether input is finite | |
Determine whether array was copied from MATLAB global workspace | |
Determine whether input is infinite | |
Determine whether array represents data as signed 16-bit integers | |
Determine whether array represents data as signed 32-bit integers | |
Determine whether array represents data as signed 64-bit integers | |
Determine whether array represents data as signed 8-bit integers | |
Determine whether array is of type mxLogical | |
Determine whether scalar array is of type mxLogical | |
Determine whether scalar array of type mxLogical is true | |
Determine whether input is NaN (Not-a-Number) | |
Determine whether array is numeric | |
Determine whether array represents data as single-precision, floating-point numbers | |
Determine whether input is sparse array | |
Determine whether input is structure array | |
Determine whether array represents data as unsigned 16-bit integers | |
Determine whether array represents data as unsigned 32-bit integers | |
Determine whether array represents data as unsigned 64-bit integers | |
Determine whether array represents data as unsigned 8-bit integers | |
Type for logical array | |
Allocate dynamic memory using MATLAB memory manager | |
Reallocate dynamic memory using MATLAB memory manager | |
Remove field from structure array | |
Value of one cell of array | |
Convert structure array to MATLAB object array | |
Set pointer to data | |
Modify number of dimensions and size of each dimension | |
Set structure array field, given structure field name and array index | |
Set structure array field, given field number and index | |
Imaginary data pointer for array | |
IR array of sparse array | |
JC array of sparse array | |
Number of rows in array | |
Set number of columns in array | |
Set storage space for nonzero elements | |
Set new imaginary data for array | |
Set new real data for array | |
Set value of public property of MATLAB object |
MEX Library
Register function to call when MEX-function cleared or MATLAB software terminates | |
Call MATLAB function, user-defined function, or MEX-file | |
Call MATLAB function, user-defined function, or MEX-file and capture error information | |
Display error message with identifier and return to MATLAB prompt | |
Display error message and return to MATLAB prompt | |
Execute MATLAB command in caller workspace | |
Execute MATLAB command in caller workspace and capture error information | |
Entry point to C/C++ or Fortran MEX-file | |
Name of current MEX-function | |
Value of specified Handle Graphics property | |
Copy of variable from specified workspace | |
Read-only pointer to variable from another workspace | |
Determine whether variable has global scope | |
Determine whether MEX-file is locked | |
Prevent clearing MEX-file from memory | |
Make array persist after MEX-file completes | |
Make memory allocated by MATLAB software persist after MEX-function completes | |
ANSI C PRINTF-style output routine | |
Array from MEX-function into specified workspace | |
Set value of specified Handle Graphics property | |
Control response of MEXCALLMATLAB to errors | |
Allow clearing MEX-file from memory | |
Warning message with identifier | |
Warning message |
参考:
http://blog.sciencenet.cn/blog-620659-579885.html
http://blog.csdn.net/raodotcong/article/details/6295859