# Using Matlab's bsxfun to subtract matrices of different sizes

My professor gave me some matlab script in which I found the following line:

differences = bsxfun(@minus, A, B);


where A is of size [200,50] and B is of size [1,50]. The documentation and forums didn't give me the answer I'm looking for. My current understanding is that every column of A matrix gets subtracted with B matrix. Is my understanding correct? Currently I don't have matlab installed which makes it a bit problematic to test myself :)

From Octave doc:

 The binary singleton expansion function applier performs
broadcasting, that is, applies a binary function F
element-by-element to two array arguments A and B, and expands as
necessary singleton dimensions in either input argument.  F is a
function handle, inline function, or string containing the name of
the function to evaluate.  The function F must be capable of
accepting two column-vector arguments of equal length, or one
column vector argument and a scalar.

The dimensions of A and B must be equal or singleton.  The
singleton dimensions of the arrays will be expanded to the same
dimensionality as the other array.


Sounds like it just expands B from [1,50] to [200,50] in the obvious way (i.e. replicating the first row of B 200 times) to make a matrix C and then performs A - C in this scenario.

Also, off-topic.

• Thanks. I deserve downvotes though. – Primož Kralj Oct 14 '13 at 20:23
• This is a part of octave behaviour which is not equivalent to Matlab. Automatic broadcasting is not done in Matlab. You can turn it off in octave if you want to be sure to write more Matlab-compatible code if you want. However it can be really convenient when you get used to it ;) – mathreadler Dec 1 '15 at 22:05