What is your favourite MATLAB/Octave programming trick? [closed]

I think everyone would agree that the MATLAB language is not pretty, or particularly consistent. But nevermind! We still have to use it to get things done.

What are your favourite tricks for making things easier? Let's have one per answer so people can vote them up if they agree. Also, try to illustrate your answer with an example.


Solution 1:

Using the built-in profiler to see where the hot parts of my code are:

profile on
% some lines of code
profile off
profile viewer

or just using the built in tic and toc to get quick timings:

tic;
% some lines of code
toc;

Solution 2:

Directly extracting the elements of a matrix that satisfy a particular condition, using logical arrays:

x = rand(1,50) .* 100;
xpart = x( x > 20 & x < 35);

Now xpart contains only those elements of x which lie in the specified range.

Solution 3:

Provide quick access to other function documentation by adding a "SEE ALSO" line to the help comments. First, you must include the name of the function in all caps as the first comment line. Do your usual comment header stuff, then put SEE ALSO with a comma separated list of other related functions.

function y = transmog(x)
%TRANSMOG Transmogrifies a matrix X using reverse orthogonal eigenvectors
%
% Usage:
%   y = transmog(x)
%
% SEE ALSO
% UNTRANSMOG, TRANSMOG2

When you type "help transmog" at the command line, you will see all the comments in this comment header, with hyperlinks to the comment headers for the other functions listed.

Solution 4:

Turn a matrix into a vector using a single colon.

x = rand(4,4);
x(:)

Solution 5:

Vectorizing loops. There are lots of ways to do this, and it is entertaining to look for loops in your code and see how they can be vectorized. The performance is astonishingly faster with vector operations!