MATLAB: USING MEX TO SPEED UP THE CODE

computationally intensivematlab codermexperformancetime

I have a matlab code which is computationally intensive and takes more than affordable time to run. I am told mex can be of help. So I have tried converting the code into its C equivalent using Matlab Coder, but am not sure how exactly to compile that in matlab now.
Please help. Thanks in advance

Best Answer

As a counterpoint, there are some issues to consider. Much of MATLAB is already compiled code, at least in the hard working parts. And what is not already compiled code is interpreted fairly efficiently. They have spent a LOT of effort to make that efficient, but there are some places where you may see gains. The result is from what has been stated here before, sometimes a gain, but sometimes even a loss in speed. Compiled code that is automatically generated need not be the most efficient code.
I see from some comments of your that your code involves multiple matrix inverses. Remember this is already something that is done by code that has been pretty heavily optimized, and it is already compiled. So if that is where your time is being spent, you will see essentially no gain from just an automatic compilation.
The net is, while you may see some gains if any, they are not going to be orders of magnitude improvements. And it may be a net loss. But if it is too slow for you, spending this effort for a 10-20% gain is arguably the wrong approach.
So what can you do for a real gain?
One option is to write your C from scratch. You need to know what you are doing, to really understand the algorithms, and to understand C. You can gain here by avoiding function call overhead, avoiding data checks, passing data more efficiently, etc.
The alternative is to work in MATLAB. And here is where you can start to make some real gains, if you can use tools like the profile tool to determine where the bottlenecks are in your code, and how to reduce/avoid them.
One approach that can sometimes be a gain is to use the parallel computing toolbox. This can be of use if the code is not already automatically using multiple cores on your machine. MATLAB often does this on bogger problems, when possible.
Best can be the algorithmic improvements. Here you can indeed find various algorithms that can offer orders of magnitude improvements. But this requires fully rethinking how you are soving the problem.
Related Question