Questions tagged [bsxfun]

A versatile and useful Matlab command for applying element-by-element binary operation to two arrays with singleton expansion enabled.

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] ) );
168 questions
136
votes
5 answers

In MATLAB, when is it optimal to use bsxfun?

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,…
Colin T Bowers
  • 18,106
  • 8
  • 61
  • 89
35
votes
1 answer

Comparing BSXFUN and REPMAT

Few questions were asked before on comparisons between bsxfun and repmat for performance. One of them was: Matlab - bsxfun no longer faster than repmat?. This one tried to investigate performance comparisons between repmat and bsxfun, specific to…
Divakar
  • 218,885
  • 19
  • 262
  • 358
25
votes
1 answer

How much faster is implicit expansion compared with bsxfun?

As commented by Steve Eddins, implicit expansion (introduced in Matlab R2016b) is faster than bsxfun for small array sizes, and has similar speed for large arrays: In R2016b, implicit expansion works as fast or faster than bsxfun in most cases. The…
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
23
votes
2 answers

Is there an equivalent to the MATLAB function bsxfun in python?

I'm trying to port some of my code from matlab to python, and some of it uses the bsxfun() function for virtual replication followed by multiplication or division (I also use it for logical operations). I'd like to be able to do this without…
Kevin
  • 343
  • 1
  • 3
  • 9
23
votes
5 answers

MATLAB tutorial for programmers

I'm getting some new students soon, who will be writing MATLAB code. They're new to MATLAB, but they have experience coding in Java and C++. I'm going to have them go through the Getting Started section of the MATLAB help. In addition, I want to…
Jonas
  • 74,690
  • 10
  • 137
  • 177
22
votes
1 answer

Matlab - bsxfun no longer faster than repmat?

I'm trying to find the fastest way of standardizing a matrix in Matlab (zero mean, unit variance columns). It all comes down to which is the quickest way of applying the same operation to all rows in a matrix. Every post I've read come to the same…
user1337
  • 494
  • 3
  • 13
22
votes
3 answers

Sort a matrix with another matrix

Suppose I have a matrix A and I sort the rows of this matrix. How do I replicate the same ordering on a matrix B (same size of course)? E.g. A = rand(3,4); [val ind] = sort(A,2); B = rand(3,4); %// Reorder the elements of B according to the…
Jacob
  • 34,255
  • 14
  • 110
  • 165
12
votes
3 answers

Converting bsxfun with @times to numpy

This is the code I have in Octave: sum(bsxfun(@times, X*Y, X), 2) The bsxfun part of the code produces element-wise multiplication so I thought that numpy.multiply(X*Y, X) would do the trick but I got an exception. When I did a bit of research I…
eTothEipiPlus1
  • 577
  • 2
  • 9
  • 28
12
votes
3 answers

How does Matlab transpose a sparse matrix?

I've been wondering about this question for quite a while but cannot find a reference: How does Matlab transpose a sparse matrix so fast, given that it is stored in CSC (compressed sparse column) format? Also its documentation verifies the…
Da Kuang
  • 852
  • 1
  • 8
  • 15
9
votes
3 answers

pdist2 equivalent in MATLAB version 7

I need to calculate the euclidean distance between 2 matrices in matlab. Currently I am using bsxfun and calculating the distance as below( i am attaching a snippet of the code ): for i=1:4754 test_data=fea_test(i,:); d=sqrt(sum(bsxfun(@minus,…
bhavs
  • 2,091
  • 8
  • 36
  • 66
8
votes
5 answers

How can I speed up this call to quantile in Matlab?

I have a MATLAB routine with one rather obvious bottleneck. I've profiled the function, with the result that 2/3 of the computing time is used in the function levels: The function levels takes a matrix of floats and splits each column into nLevels…
Chris Taylor
  • 46,912
  • 15
  • 110
  • 154
8
votes
1 answer

Is bsxfun usable with sparse matrices

I want to a element-by-element binary operation apply to large logical vectors. The content of these vectors is manly false, so for performance considerations it better to work with sparse matrices. If i do so the resulting matrix is not…
Tobias Heß
  • 268
  • 1
  • 9
8
votes
4 answers

Generalized Matrix Product

I'm fairly new to MATLAB. Normal matrix multiplication of a M x K matrix by an K x N matrix -- C = A * B -- has c_ij = sum(a_ik * b_kj, k = 1:K). What if I want this to be instead c_ij = sum(op(a_ik, b_kj), k = 1:K) for some simple binary operation…
Nick
  • 2,821
  • 5
  • 30
  • 35
8
votes
3 answers

Matlab's bsxfun() - what explains the performance differences when expanding along different dimensions?

In my line of work (econometrics/statistics), I frequently have to multiply matrices of different sizes and then perform additional operations on the resulting matrix. I have always relied on bsxfun() to vectorize the code, which in general I find…
IvanT
  • 91
  • 5
7
votes
2 answers

Matlab - Singleton expansion for more than two inputs

I have a function that takes in more than 2 variables eg. testFunction = @(x1, x2, x3, x4) x1.*x2.*x3.*x4; testFunction2 = @(x1, x2, x3) sin(x1.*x2.^x3); Is there a function available like bsxfun that allows singleton expansion for functions…
1
2 3
11 12