# 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:

**Terrible:** `A = trace(V*V'); % I have been guilty of this(!)`

**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.
Caveats: `naninf`

does not work in Octave yet and in Matlab only works for
functions, not scripts.

Complex numbers are also a pain when not
intended. Get `log`

and `sqrt`

to throw errors rather than create
complex numbers 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.**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.