As mentioned recently by Nick, repmat is a nice way to duplicate some arrays around multiple dimensions and avoid some for loops. It is quite a flexible and general approach that not only limits to processing row by row (or column by column). You can also replicate various subarrays. However, if your particular application is to process an array either element by element or along one of its dimension, then bsxfun is a faster alternative, as pointed by both Nick on this blog and Loren on her own, especially since bsxfun is now multithreaded in Matlab. Another advantage of bsxfun is that it does not require to allocate an intermediate large matrix. If your particular application is demanding on memory, than it is definitely going to be faster for you.
Besides, there are really no reason not to use it as it is an easier alternative in most cases. Our previous example was, given a NxT matrix Trials :
N=100; T=1000; Trials=rand(N,T); for i=1:N AverageValue=mean(Trials(i,:)); Trials(i,:)=Trials(i,:)-AverageValue; end
The equivalent with bsxfun is :
N=100; T=1000; Trials=rand(N,T); AverageValue=mean(Trials,2); Trials=bsxfun(@minus,Trials,AverageValue);
As indicated on the doc, bsxfun applies @minus to 2 matrices A and B (here A is Trials and B is AverageValue). All dimensions of A and B must be the same or singletons. bsxfun will automatically duplicates arrays (in a way automatically applies repmat) so that the operation (here minus) can be applied on all single elements. ‘@’ is used to give a function handle. A function handle is like a pointer that gives to Matlab the address to a particular function that can take both A and B as inputs. There are a number of built-in handles that you can pass to bsxfun. Most standard operations are there. You can also create your own as long as you respect its syntax.