How to optimize MATLAB loops?

Lately, I have been working on several iterative algorithms in MATLAB and have been hit hard on MATLAB's performance (or lack thereof) when it comes to loops. I know the benefits of code vectoring whenever possible, but are there any optimization tools when you need a loop for your algorithm?

I am aware of the MEX file option for writing small routines in C / C ++, although, given my algorithms, this can be a very painful option, given the required data structures. I mainly use MATLAB for simplicity and speed of prototyping, so a syntactically complex, statically typed language is not ideal for my situation.

Are there any other suggestions? Even other languages ​​(python?), Which have relatively painless matrix tools, are an option.

+4
source share
5 answers

It was once true that vectorization will improve the speed of your MATLAB code. However, this is largely untrue to the JIT-accelerator

This video demonstrating the MATLAB profiler can help.

+4
source

PROFILER is a very useful tool for finding bottlenecks in Matlab code. it does not change your code, but helps to find which functions / lines to optimize using vectorization or mex.

http://www.mathworks.com/access/helpdesk/help/techdoc/ref/profile.html

http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_env/f9-17018.html

+4
source

You might want to explore the MATLAB Parallel Computing Toolbox, which can make a big difference if you have the right hardware. I rewrote about 12 lines of code and got acceleration 4-6 times for one of our programs with an intensive cycle and an eight-core PC.

+3
source

If you have a choice, be sure to tweak your loops so that you scan the data column as the data in MATLAB does. Also, be sure to preallocate any output arrays before the loop and index in them instead of growing the array inside the for loop.

+3
source

If you can use your code to invoke your operations throughout the matrix, you will see a significant improvement in the speed of your code. Many functions are performed much faster when working on the entire matrix, and not in an elementary form with cycles.

+3
source

Source: https://habr.com/ru/post/1302781/


All Articles