(转)matlab与C的混合编程之入门

这里仅讲述matlab调用C的混合编程,暂不涉及C调用matlab的混合编程。

mtalab第一次调用C编程之前,需运行mex操作,此操作在windows系统下是一个bat的批处理文件,在unix系统下是个shell脚本。

>> mex -setup             //在matlab 的command window下运行此命令
Please choose your compiler for building external interface (MEX) files:
 
Would you like mex to locate installed compilers [y]/n? y  //是否调用本地安装好的c编译软件

 
Select a compiler:
[1] Lcc-win32 C 2.4.1 in C:\PROGRA~1\MATLAB\R2010b\sys\lcc
[2] Microsoft Visual C++ 6.0 in C:\Program Files\Microsoft Visual Studio
 
[0] None
 
Compiler: 1    //也可以选择2
 
Please verify your choices:
 
Compiler: Lcc-win32 C 2.4.1
Location: C:\PROGRA~1\MATLAB\R2010b\sys\lcc
 
Are these correct [y]/n? y     //确认正确
 
Trying to update options file: C:\Users\XJT\AppData\Roaming\MathWorks\MATLAB\R2010b\mexopts.bat
From template:              C:\PROGRA~1\MATLAB\R2010b\bin\win32\mexopts\lccopts.bat
 
Done . . .
 
**************************************************************************
  Warning: The MATLAB C and Fortran API has changed to support MATLAB
           variables with more than 2^32-1 elements.  In the near future
           you will be required to update your code to utilize the new
           API. You can find more information about this at:
           http://www.mathworks.com/support/solutions/en/data/1-5C27B9/?solution=1-5C27B9
           Building with the -largeArrayDims option enables the new API.
**************************************************************************
 
>>

到此,matlab调用C的混合编程环境已经搭建好,下面举个简单例子:


#include <mex.h>
void mexFunction(int nlhs ,mxArray *plhs[] ,int nrhs, const mxArray *prhs[])
{
    mexPrintf("Hello word!");
}

把上面程序保存为一个C文件,如    hello.c

在command window下运行

>> mex hello.c
>>

结束之后在current folder 窗口里会有一个hello.mexw32文件。

在command window下运行

>> hello()
Hello word!

至此,一个简单的hello word程序已经完成。

在下一篇,会进行稍微深入的讲解如何编写C文件。

posted @ 2013-01-22 17:19  milier_otw  阅读(268)  评论(0)    收藏  举报