简述
matlab比较擅长矩阵运算,而运算for的速度较慢,如果将matlab与C或C++进行混合编程,则可以提升程序运行速度。matlab与C/C++的混合编程是通过mexFunction进行的,即在C或C++的源文件中添加一个mexFunction函数,然后通过MX矩阵库和MEX函数库进行编程,我们先来查看matlab给的例子。
mexFunction的编写
#include "mex.h"
void
mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
mxArray *cell_array_ptr, *rhs[1];
mwIndex i;
(void)plhs; /* unused parameter */
/* Check for proper number of input and output arguments */
if (nrhs < 1) {
mexErrMsgIdAndTxt( "MATLAB:mxcreatecellmatrix:minrhs",
"At least one input argument required.");
}
if(nlhs > 1){
mexErrMsgIdAndTxt( "MATLAB:mxcreatecellmatrix:maxlhs",
"Too many output arguments.");
}
/* Create a nrhs x 1 cell mxArray. */
cell_array_ptr = mxCreateCellMatrix((mwSize)nrhs,1);
/* Fill cell matrix with input arguments */
for( i=0; i<(mwIndex)nrhs; i++){
mxSetCell(cell_array_ptr,i,mxDuplicateArray(prhs[i]));
}
rhs[0] = cell_array_ptr;
/* Call mexCallMATLAB to display the cell */
mexPrintf("\nThe contents of the created cell is:\n\n");
mexCallMATLAB(0,NULL,1,rhs,"disp");
}
此示例显示如何使用mxCreateCellMatrix.c函数在MEX文件中创建单元格数组,然后将输入参数放入单元格数组中,并在matlab命令窗口中输出。
首先在代码中引入mex.h头文件,接着编写mexFunction。函数中的四个参数分别表示,输出的个数(left hand side),指向输出变量的mxArray的指针数组,输入的个数(right hand side),指向输入变量的mxArray的指针数组。函数里面的mx和mex开头的类型和方法皆为mx函数库和mex函数库所提供。
VS调试
编写好C/Cpp文件后,将matlab的当前路径切换到C/Cpp所在的文件夹下,然后在命令窗口或脚本文件中输入mex mxcreatecellmatrix.C/Cpp,这样就可以在matlab中调用mxcreatecellmatrix函数,如下图:
其中,我们还可以利用VS2010对源文件调试,步骤如下:
1.切换到Cpp文件所在路径,在命令窗口中输入mex -g mxcreatecellmatrix.cpp
2.打开VS2010,选择工具->附加到进程,如下图:
3.找到matlab.exe,选中,点击附加
注意此时不要关闭matlab.
4.选择文件,打开有mexFunction的CPP文件,然后设置断点
5.在matlab的命令窗口中输入:mxcreatecellmatrix(‘123’,’456’),接着就可以采用VS进行调试。
mx函数库
这里给出部分mx函数的用途,其余的可自行查看matlab的帮助文档:
函数 | 用途 |
---|---|
mxIsUint8 | 确定数组是否将数据表示为无符号8位整数 |
mxIsDouble | 确定mxArray是否将数据表示为双精度浮点数 |
mexErrMsgTxt | 显示错误消息并返回到MATLAB命令窗 |
mxGetNumberOfDimensions | 获取数组中的维数 |
mxGetDimensions | 获取指向数组维度的指针 |
mxGetScalar | 数组中第一个数据元素的实数组成部分 |
mxGetData | 数组中数值数据元素的指针 |
mxCreateDoubleMatrix | 创建2维,双精度,浮点数组 |
mxGetPr | DOUBLE类型的数组中的实数数据元素 |
mxCreateCellMatrix | 创建二维的元胞数组 |
mexPrintf | 在command window和日记中打印字符串(如果日记正在使用中) |