matlab和C++混合编程

一、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
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值