Описание тега bsxfun
bsxfun
(binary singleton expansion function) is a built-in Matlab function that allows for applying an element-by-element binary operation to two arrays with singleton expansion enabled. It can be used to avoid unnecessary and costly calls to repmat
, and to replace specific for-loop structures.
See the current documentation for bsxfun
. The function debuted in Matlab 7.4 (R2007a). Those with versions of Matlab prior to this can try this bsxfun substitute on the MathWorks File Exchange.
What can be done with bsxfun
?
The following examples demonstrate all sorts of useful and efficient uses of bsxfun
.
Normalizing vectors
Suppose you have a collection of n
feature vectors with dimension d
in a 2D matrix feat
of size n
-by-d
. You wish to normalize all the features to have Euclidean norm of 1.
Here's how it can be done with bsxfun
:
>> l2norm = sqrt( sum( feat.^2, 2 ) ); % n-by-1 vector of the norms of the feature vectors
>> normFeat = bsxfun( @rdivide, feat, l2norm ); % ta-da!
Subtracting vectors
Suppose you have n
d
dimensional vectors and you wish to find their distance from some predefined location c
.
Here's how it can be done with bsxfun
:
>> dst = sqrt( sum( bsxfun( @minus, vectors, c ).^2, 2 ) );
Creating a logical triangular matrix
What if you have a matrix A
of n
-by-n
and you want a logical matrix L
that selects the lower triangle of A
(that is L(ii,jj)
is true iff ii > jj
)?
Here's how it can be done with bsxfun
:
>> L = bsxfun( @gt, (1:n)', 1:n );
Computing the outer-product of many vectors simultaneously
Suppose you have two collections of n
factors of d
dimension U
and V
(both of size n
-by-d
), and you want to compute the outer-product O(:,:,ii) = U(ii,:)'*V(ii,:)
for all the n
vector-pairs.
Here's how it can be done with bsxfun
:
>> O = bsxfun( @times, permute( U, [3 2 1] ), permute( V, [2 3 1] ) );