MATLAB编译并调用C、C++程序

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
窗口中,输入: >>mex test.cpp ,若程序有错,会有提示,若无错,
会在 test.cpp 的旁边生成 test.mexw32 文件,这个文件可以供 MATLAB
调用实现 test.cpp 中的 C、C++函数的功能。
在 MATLAB 中调用 C、C++程序:
将 MATLAB 的工作目录切换至上面已编译好的 test.mexw32 所在的目
}
dbX = mxGetScalar( prhs[ 0 ] ); dbY = mxGetScalar( prhs[ 1 ] );
/* Create matrix for the return argument. */ plhs[0] = mxCreateDoubleMatrix( mrows, ncols, mxREAL ); plhs[1] = mxCreateDoubleMatrix( mrows, ncols, mxREAL );
mrows = mxGetM(prhs[0]); ncols = mxGetN(prhs[0]); if ( mxIsComplex(prhs[0]) ||
!(mrows == 1 && ncols == 1)) {
mexErrMsgTxt("The First input must be a noncomplex scalar double precision.");
/* Assign pointers to each input and output. */ pdbA = mxGetPr( plhs[0] ); pdbG = mxGetPr( plhs[1] );
Desc2Pol( dbX, dbY, pdbA, pdbG ); }
将 MATLAB 的工作目录切换至 test.cpp 所在目录,在 MATLAB 的命令
MATLAB 编译并调用 C、C++程序
MATLAB 的 C、C++程序编译器的设置:
在命令窗口中输入: >>mex -setup ,接着按照提示进行即可完成 C、
C++程序编译器的设置。
在 MATLAB 中编译 C、C++程序:
C、C++程序的格式以 test.cpp 为例,如下示:
#include "mex.h" //必须 #include <math.h>
*pdbG = -90; } else {
*pdbG = 90; } } else { *pdbG = atan( dbX/dbY ); } }
//Matlab的接口函数,必须而且格式也一样 void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) {
mexErrMsgTxt("Two input required."); }
//必须是2个输出参数 //包括 if ( nlhs != 2 ) {
mexErrMsgTxt("Two output required."); }
/* Check for proper type of arguments . 检查输入、输出参数类型 */
double dbX = double dbY = double *pdbA = double *pdbG =
0; 0; NULL; NULL;
/* Check for proper number of arguments. 检查输入、输出参数个数 */
//必须是2个输入参数 //包括 if ( nrhs != 2 ) {
//程序功能实现函数 void Desc2Pol ( double dbX, double dbY, double *pdbA, double *pdbG ) {
*pdbA = sqrt(dbX * dbX + dbY * dbY ); if (dbY == 0 ) {
if ( dbX < 0 ) {
includemexh必须includemathh程序功能实现函数voiddesc2poldoubledbxdoubledbydoublepdbadoublepdbgatandbxdbymatlab的接口函数必须而且格式也一样voidmexfunctionintnlhsmxarrayplhsintnrhsconstmxarrayprhs其中nlhs为在matlab环境中调用该函数时要求返回参数的个数nrhs为在matlab环境中调用该函数时输入参数的个数plhs在matlab环境中调用该函数时要求返回参数的队列prhs在matlab环境中调用该函数时输入参数的队列intmrowsintncolsdoubledbxdoubledbydoublepdbanull
录,在 MATLAB 的命令窗口中输入: >>[a b] = test(1,1); 即可实
现调用 C、C++程序。
}
mrows = mxGetM( prhs[ 1 ] ); ncols = mxGetN( prhs[ 1 ] ); if ( mxIsComplex( prhs[ 1 ] ) ||
!(mrows == 1 && ncols == 1 ) ) {
mexErrMsgTxt("The fourth input must be a noncomplex scalar double precision.");
/* 其中nlhs为在Matlab环境中调用该函数时要求返回参数的个数 nrhs为在Matlab环境中调用该函数时输入参数的个数
plhs在Matlab环境中调用该函数时要求返回参数的队列 prhs在Matlab环境中调用该函数时输入参数的队列 */
int mrows = 0; iБайду номын сангаасt ncols = 0;
相关文档
最新文档