In MATLAB, when is it optimal to use bsxfun?
Asked 07 September, 2021
Viewed 608 times
  • 57
Votes

I've noticed that a lot of good answers to MATLAB questions on Stack Overflow frequently use the function bsxfun. Why?

Motivation: In the MATLAB documentation for bsxfun, the following example is provided:

A = magic(5);
A = bsxfun(@minus, A, mean(A))

Of course we could do the same operation using:

A = A - (ones(size(A, 1), 1) * mean(A));

And in fact a simple speed test demonstrates the second method is about 20% faster. So why use the first method? I'm guessing there are some circumstances where using bsxfun will be much faster than the "manual" approach. I'd be really interested in seeing an example of such a situation and an explanation as to why it is faster.

Also, one final element to this question, again from the MATLAB documentation for bsxfun: "C = bsxfun(fun,A,B) applies the element-by-element binary operation specified by the function handle fun to arrays A and B, with singleton expansion enabled.". What does the phrase "with singleton expansion enabled" mean?

5 Answer