speed up m-file with mex
2 views (last 30 days)
Show older comments
I find many example of mex, but all of examples I found are that all of the methods to write code just like C code and without calling any matlab bulit-in function. Does m-file can not be transformed to mex file? I tried to do this, but it present the result that is not successful.
2 Comments
Answers (2)
Jan
on 18 Aug 2015
You can call Matlab from C: mexCallMATLAB. But this has a measurable overhead. So better create a pure C-Mex file for the bottleneck of the code and avoid hopping back to Matlab.
2 Comments
Walter Roberson
on 28 Aug 2015
"mex" is a command for compiling external code that might be written in C or C++ or Fortran (or any other compatible language), and arranging that compiled machine code so that it can be called as an extension from MATLAB.
"mex" does not provide the facility to compile MATLAB code into machine code.
The product that allows some portions of MATLAB to be converted into C or C++, that could then be compiled into machine code, is MATLAB Coder.
You may also have seen reference to MATLAB Compiler. It does not compile MATLAB code into machine code: instead internally it is like MATLAB without the command line, to allow single-purpose programs to be distributed without the recipients needing to own MATLAB licenses. MATLAB Compiler executables are the same speed as MATLAB, executing the same way.
If you have a section of MATLAB code that you need to speed up, the first thing you should do is profile it to figure out where the parts are that take the most time. Examine those parts first. Determine whether there might be a faster approach, such as using vectorization. Experiment.
If you identify a section that takes a long time in MATLAB and that you cannot find a way to speed up in MATLAB, then you can write C or C++ code to perform the same operations, and then have MATLAB call that C or C++ code. "mex" would be used as part of that.
If you want to have a program translate your MATLAB code into C or C++, instead of you spending your time writing that code yourself, then you need the MATLAB Coder product. It is expensive. It is also only available for the Academic or Professional / Commercial licenses. MATLAB Coder does not support all MATLAB facilities. It also takes effort to do a proper conversion even with MATLAB Coder, writing in hints to reduce ambiguity that MATLAB would normally resolve at execution time.
See Also
Categories
Find more on MATLAB Compiler in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!