Using Matlab's bsxfun to subtract matrices of different sizes

1.3k Views Asked by At

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

1

There are 1 best solutions below

2
On BEST ANSWER

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.