如果你是需要快速搭建一个matlab调c/c++环境,这篇文章可以参考
有了c代码,想在matlab里面调用,可以参考我这个模板
matlab调用代码:
clear all
close all
clcinput1 =1;
input2 =2;[output1,output2] = mexfunction(input1,input2);output1
output2
这里面强调两个概念
1、Matlab里面所有变量都是矩阵,包括单变量也是1*1的矩阵
2、Maltab矩阵按列优先访问,这个和fortran保持一致
Cpp代码:
#include "mex.h"void c_func(double input1,double input2,double *output1,double *output2)
{}void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{ double *pdata; // mcnoidal(waveheight,waveperiod,0.02,waterdeepth ,0, datanum,1, waveheight,flapdeepth);pdata=mxGetPr(prhs[0]); double input1 = *pdata;int M = mxGetM(prhs[0]);int N = mxGetN(prhs[0]);printf("%d * %d\n",M,N);pdata=mxGetPr(prhs[1]); double input2 = *pdata;int m = 3;int n = 2;plhs[0] = mxCreateDoubleMatrix(m, n, mxREAL); double *output1; output1 = mxGetPr( plhs[0]);//列优先排列output1[0*m+0] = 1;output1[1*m+0] = 2;output1[0*m+1] = 3;output1[1*m+1] = 4;output1[0*m+2] = 5;output1[1*m+2] = 6; plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL); double *output2;output2 = mxGetPr( plhs[1]);output2[0] = -1;//c_func(input1,input2,output1,output2) ;}
plhs 全称 parameters left matlab中的左侧输出值
prhs全称 parameters left matlab中的右侧输入值
plhs[0] plhs[1]是输出,需要多少输出变量,那么就在c中用mxCreateDoubleMatrix申请多少
所有的数字,数组,二位数字,到c这边都是一维数组,且按列优先访问。
输出如下
注三行两列的二维数组访问方式:
int m=3;
int n=2;
//内存列优先排列,但赋值按逐行赋值
output1[0*m+0] = 1;
output1[1*m+0] = 2;
output1[0*m+1] = 3;
output1[1*m+1] = 4;
output1[0*m+2] = 5;
output1[1*m+2] = 6;//列优先排列,但按列赋值
output1[0*m+0] = 1;
output1[0*m+1] = 3;
output1[0*m+2] = 5;
output1[1*m+0] = 2;
output1[1*m+1] = 4;
output1[1*m+2] = 6;//另:行优先排列,按行赋值
output1[0*n+0] = 1;
output1[0*n+1] = 2;
output1[1*n+0] = 3;
output1[1*n+1] = 4;
output1[2*n+0] = 5;
output1[2*n+1] = 6;
在matlab 使用mex 编译一下(预先需要mex setup)
mex mexFunction.cpp 即可编译,然后在malab直接调用。