一、matlab和mexFunction数据交换
下面举个例子,
例1.编写hello.c文件如下:
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
mexPrintf("Hello World!\n");
}
在matlab命令行使用mex编译,如下:
>> mex hello.c
>> hello
Hello World!
>>
我们看到,当在命令行>>hello时,输出了Hello,World!。
例2.函数的使用ex1.c
# include "mex.h"
# include "matrix.h"
//mxCreateCharMat rixFromStrings 函数的使用方法
void mexFunction(int nlhs, mxArray * plhs[ ] , int nrhs , const mxArray * prhs[ ] )
{
char s1[ ] = "Bei Jing" ;
char s2[ ] = "Shang Hai" ;
char s3[ ] = "Tian Jin" ;
char s4[ ] = "Chong Qing" ;
char * s[4] = {s1 ,s2 , s3 , s4} ;
mxArray * charArray;
/* 创建一个4×10 字符矩阵, 其内容如下:
Bei Jing
Shang Hai
Tian Jin
Chong Qing
*/
charArray =mxCreateCharMatrixFromStrings(4 , s) ;
//如果输出参数为1
if(nlhs == 1 )
{
plhs[0] = charArray;
}
else
{
mexPrintf( "输出阵列的个数错误! \n" ) ;
mxDestroyArray( charArray) ;
}
}
结果:
>> mex ex1.c
>> ex1
输出阵列的个数错误!
>> a=ex1
a =
Bei Jing
Shang Hai
Tian Jin
Chong Qing
>>
例3. ex2.c
/*
*要求:如[ABCD;EFGH],返回的字符串是"AEBFCGDH"
*利用mxGetStr