Octave and Matlab tricks
Below are notes on a few programming issues that crop up a lot. You might also want to check out my much longer page on efficient Matlab/Octave programming. See also Tom Minka’s lightspeed Matlab toolbox. Also see my own modest toolbox of Octave/Matlab code.
Not all vectorizations are equal:
A = trace(V*V'); % I have been guilty of this(!)
A = sum(sum(V.*V));
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.
w = inv(X)*y;
w = X\y
See also functions in Lightspeed.
Inefficient for huge matrices:
X = X + diag(y); % where y is a vector
X = plus_diag(X, y);
Debugging out-of-bound numbers:
dbstop if naninf;
will let you catch
Inf’s at source.
naninf does not work in Octave yet and in Matlab only works for
functions, not scripts.
Complex numbers are also a pain when not
sqrt to throw errors rather than create
complex numbers with:
log=@reallog; sqrt=@realsqrt; — in octave you'll have
to provide reallog.m
If memory is too tight for a naive
repmat: have a
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.
Actually, use bsxfun routinely: I have found it very useful; bsxfun often gives cleaner, faster code than using repmat. If you send your code to someone with an old version of Matlab, they can use this simple replacement, which is implemented with repmat.
Update 2019: you don't need bsxfun either: both Matlab and Octave have now supported broadcasting for a while, making bsxfun crufty line-noise of the past.