Matlab中mex与C混合编程总结

来源:互联网 发布:北京致远协创软件 编辑:程序博客网 时间:2024/05/16 10:53

使用mex和C可以加快算法的运行速度,mex文件包含一个入口函数如下:

void mexFunction( int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[] ) 
入口函数有四个参数:prhs为mxArray结构体类型的指针数组,该数组的元素按顺序指向所有的输入参数;
nrhs为整数类型,它标明了输入参数的个数。
plhs:为mxArray结构体类型的指针数组,该数组的元素按顺序指向所有的输出参数;
nlhs:输出参数的个数

在入口程序完成两件事情:第一:从输入的mxArray结构体中获得计算完毕的数据,然后在用户的子程序中加以使用
第二:用户可以将计算完毕的结果返回给一个用于输出的mxArray结构体。
mex源文件的两个组成部分可以分为两个文件也可以放在一个文件中,必须包含mex.h头文件,该头文件包含matrix.h和一些
以mex开头的子函数。

下面举几个例子:

#include "mex.h"/* 输入参数 */#defineMInputprhs[0]     /* 输出参数 */#define OUTMplhs[0]void mexFunction( int nlhs, mxArray *plhs[],     int nrhs, const mxArray *prhs[] )          {            int i,j,N,L;            double *Input,*output;            if (nrhs < 1)           {    mexErrMsgTxt("至少需要一个参数!");           }        Input= mxGetPr(MInput); /*获取矩阵*/  N = mxGetM( MInput ); /*获取矩阵的行*/L = mxGetN( MInput); /*获取矩阵的列*/for( i=0;i<N;i++) /*一行一样输出*/{    for ( j=0;j<L;j++)     printf("%f ", Input[i+j*N]);/*若索引从1开始则变成i-1+(j-1)*N MATLAB 是按列存数据 */           printf("\n"); /*输出完一行,换行*/}     OUTM= mxCreateDoubleMatrix(N,L, mxREAL); /* 建立输出矩阵*/ output=mxGetPr(OUTM);  for( i=0;i<N;i++) /*一行行的赋值*/{    for ( j=0;j<L;j++)    output[i+j*N]=Input[i+j*N];/*若索引从1开始则变成i-1+(j-1)*N*/        }  }

下面是字符串的操作:

#include "mex.h"   voidmexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]){    char *buf;    mwSize buflen;    int status;    (void) plhs;    /* unused parameters */        /* Check for proper number of input and output arguments */    if (nrhs != 1) { mexErrMsgTxt("One input argument required.");    }     if (nlhs > 1) {mexErrMsgTxt("Too many output arguments.");    }        /* Check for proper input type */    if (!mxIsChar(prhs[0]) || (mxGetM(prhs[0]) != 1 ) )  {mexErrMsgTxt("Input argument must be a string.");    }        /* Find out how long the input string is.  Allocate enough memory       to hold the converted string.  NOTE: MATLAB stores characters       as 2 byte unicode ( 16 bit ASCII) on machines with multi-byte       character sets.  You should use mxChar to ensure enough space       is allocated to hold the string */        buflen = mxGetN(prhs[0])*sizeof(mxChar)+1;    buf = mxMalloc(buflen);        /* Copy the string data into buf. */     status = mxGetString(prhs[0], buf, buflen);       mexPrintf("The input string is:  %s\n", buf);    /* NOTE: You could add your own code here to manipulate        the string */        /* When finished using the string, deallocate it. */    mxFree(buf);    }

动态分配内存的例子:

#include "mex.h"/* The mxArray in this example is 2x2 */#define ROWS 2#define COLUMNS 2#define ELEMENTS 4void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {    double  *pointer;          /* pointer to real data in new array */    double  *dynamicData;      /* pointer to dynamic data */    const double data[] = {2.1, 3.4, 2.3, 2.45};  /* existing data */    mwSize index;/* Check for proper number of arguments. */    if ( nrhs != 0 ) {        mexErrMsgIdAndTxt("MATLAB:arrayFillGetPrDynamicData:rhs","This function takes no input arguments.");    }     /* Create a local array and load data */    dynamicData = mxMalloc(ELEMENTS * sizeof(double));    for ( index = 0; index < ELEMENTS; index++ ) {        dynamicData[index] = data[index];    }    /* Create a 2-by-2 mxArray; you will copy existing data into it */    plhs[0] = mxCreateNumericMatrix(ROWS, COLUMNS, mxDOUBLE_CLASS, mxREAL);    pointer = mxGetPr(plhs[0]);    /* Copy data into the mxArray */    for ( index = 0; index < ELEMENTS; index++ ) {        pointer[index] = dynamicData[index];    }    /* You must call mxFree(dynamicData) on the local data.       This is safe because you copied the data into plhs[0] */    mxFree(dynamicData);        return;}


复制搜索
原创粉丝点击