Octave and Matlab tricks

Elsewhere

Check out Marios Athineos’s page and Tom Minka’s lightspeed Matlab toolbox. (Personally I’ve stuck with an old version of lightspeed, which has a more liberal MIT-style license.)

Here

Just a couple of things that crop up a lot:


Not all vectorizations are equal:

Terrible: A = trace(V*V');
Better: A = sum(sum(V.*V));
Best: A = V(:)'*V(:);

Don’t compute things you don’t need (if you can help it). Check .*’s inside sums to see if they can be changed into a * without the sum.


Not great: w = inv(X)*y;
Better: w = X\y

See also functions in Lightspeed.


Inefficient for huge matrices: X = X + diag(y); % where y is a vector
Better: X = plus_diag(X,y);
Using plus_diag.m


Debugging out-of-bound numbers: dbstop if naninf; will let you catch NaN’s and Inf’s at source (in Matlab, sadly not yet in Octave). Complex numbers are also a pain when not intended, get log and sqrt to throw errors rather than create them with: log=@reallog; sqrt=@realsqrt; — in octave you'll have to provide reallog.m and realsqrt.m.


If memory is too tight for a naive repmat: have a look at bsxfun, it may be useful. The alternative is to start chunking the operation up in loops, or writing mex files. Having a new standard Matlab function (now in Octave too) for avoiding this mess is nice.