Matlab和C程序的备忘2

来源:互联网 发布:unity3d 重力感应 编辑:程序博客网 时间:2024/04/29 04:01

继续添加学习备注。

matlab提供了调用C的接口,只需要按照matlab的要求来编写程序即可。他要求的入口函数是
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const *mxArray *prhs[])

nlhs代表函数返回的变量个数,这些变量都是mxArray类型的,然后每个变量的地址都在plhs数组中。nrhs是函数的输入参数的个数,每个参数在进入mexFunction之前,都已经被matlab弄成mxArray类型的了,他们的地址也都在prhs中。

那么首先第一步就是,我们在matlab中调用这个函数了,起码在mexFunction中得到这个函数的参数值,以便接下来继续操作。从这个开始,假定我在matlab调用的函数是d,调用的格式为d(a, 3),其中a是一个2 x 8的matrix,也就是说类似:
data = [0 0 0 0 0 0 0 0;
0 1 1.5 4 5 8 9 10];
k = 3;
d(data, k)
那么在mexFunction中第一部就是得到这个data,那么具体的代码就是:

#include "mex.h"void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){    double *data1 = mxGetPr(prhs[0]);    double *k1 = mxGetPr(prhs[1]);    int k = (int)*k1; // how many points we need to retain    int m = (int)mxGetM(prhs[0]);    int n = (int)mxGetN(prhs[0]);    mexPrintf("m:%d,n:%d\n", m, n);}

打印出来是m:2,n:8。

再加上几句话,就是把输入的参数转化成C里面可以用的多维数组,接着我们只需要在这个多维数组进行操作就行了,就这么来:

#include "mex.h"void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){    double *data1 = mxGetPr(prhs[0]);    double *k1 = mxGetPr(prhs[1]);    int k = (int)*k1; // how many points we need to retain    int m = (int)mxGetM(prhs[0]);    int n = (int)mxGetN(prhs[0]);    // create a matrix to save the input data    mxArray *data_ptr = mxCreateDoubleMatrix((size_t)m, (size_t)n, mxREAL);    double *data = mxGetPr(data_ptr);    int i, j;    for (i = 0; i < n; i++)    {        for (j = 0; j < m; j++)        {            data[i*m+j] = data1[i*m+j];        }    }}

此时这个文件中的data的内容就和我们输入的参数矩阵完全一样啦。
那如果我想把这个data返回怎么办?很easy,只需要在下面加上两句话:

nlhs = 1;plhs[0] = data_ptr;

好了,这个里面完成了matlab和C的打交道了,里面就是自己的操作了。

0 0
原创粉丝点击