Skip to content

Instantly share code, notes, and snippets.

@evandrix
Created September 3, 2012 05:20
Show Gist options
  • Save evandrix/3606904 to your computer and use it in GitHub Desktop.
Save evandrix/3606904 to your computer and use it in GitHub Desktop.
Optimising MATLAB
mlint, mex (C/C++ bridge)
Vectorize sensibly.
Use `bsxfun` in lieu of `repmat` where possible.
loop access arrays/matrix data in column-major order to maximize cache hits, since this is the same
order that MATLAB stores the data in
Profile the code
Pay attention to messages from the Code Analyzer.
Use functions instead of scripts.
Don't "poof" variables into any workspaces. Translation, don't use load without a left-hand side;
avoid eval, evalin, and assignin.
Use logical indexing instead of find.
Avoid global variables.
Don't use equality checks with floating point values.
Use left hand zeros: 0.5 instead of .5
I try to avoid using variables and function names that are common terms like, ans, mean, filter,
etc… If there is any doubt, use the `which` command to find out if a function exists of a given name.
Use whitespace for code layout
Meaningful variable names: flagPassedInspection, centroidX, fidCurrentFile
Avoid hardcoding large data into MATLAB code
Break code into logical sections, each 1 screen long max.
---
The following provides information on tools within MATLAB that can help you optimize the performance
of your code.
1. The first step is to analyze the performance of your MATLAB code in its current state. The
following is a link to the documentation regarding this topic:
http://www.mathworks.com/help/techdoc/matlab_prog/f8-790895.html
In particular, the MATLAB Profiler measures where a program spends time and generates a summary. By
using the Profiler, you can determine which commands and which lines of code are taking the longest
to execute, and therefore determine where you can focus most of your optimization efforts. To read
about how to use the MATLAB Profiler to improve performance, please see the following link:
http://www.mathworks.com/help/techdoc/matlab_env/f9-17018.html
2. There is a section in the documentation that discusses best practices for writing highly
efficient code, including when and how to vectorize, how to preallocate memory for arrays,
http://www.mathworks.com/help/techdoc/matlab_prog/f8-784135.html
3. Multithreading comes default enabled in the most recent version of MATLAB. Common mathematical
operations are programmed to make use of multithreading. For a list of the affected functions, see
the Related Solution at the bottom of this page.
To find out if the Parallel Computing Toolbox can help make best use of a multiple core desktop or a
computing cluster, navigate to the following link:
http://www.mathworks.com/help/toolbox/distcomp/f3-6010.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment