Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Very interesting question! I have recently stumbled upon exactly such situation while answering <a href="https://stackoverflow.com/questions/12867524/matlab-calculation-on-subset-of-vector-then-shift-and-repeat/12872704#12872704">this</a> question. Consider the following code that computes indices of a sliding window of size 3 through a vector <code>a</code>:</p> <pre><code>a = rand(1e7,1); tic; idx = bsxfun(@plus, [0:2]', 1:numel(a)-2); toc % equivalent code from im2col function in MATLAB tic; idx0 = repmat([0:2]', 1, numel(a)-2); idx1 = repmat(1:numel(a)-2, 3, 1); idx2 = idx0+idx1; toc; isequal(idx, idx2) Elapsed time is 0.297987 seconds. Elapsed time is 0.501047 seconds. ans = 1 </code></pre> <p>In this case <code>bsxfun</code> is almost twice faster! It is useful and fast because it <strong>avoids explicit allocation of memory</strong> for matrices <code>idx0</code> and <code>idx1</code>, saving them to the memory, and then reading them again just to add them. Since memory bandwidth is a valuable asset and often the bottleneck on todays architectures, you want to use it wisely and decrease the memory requirements of your code to improve the performance.</p> <p><code>bsxfun</code> allows you to do just that: create a matrix based on applying an arbitrary operator to all pairs of elements of two vectors, instead of operating explicitly on two matrices obtained by replicating the vectors. That is <em>singleton expansion</em>. You can also think about it as the <strong>outer product</strong> from BLAS:</p> <pre><code>v1=[0:2]'; v2 = 1:numel(a)-2; tic; vout = v1*v2; toc Elapsed time is 0.309763 seconds. </code></pre> <p>You multiply two vectors to obtain a matrix. Just that the outer product only performs multiplication, and <code>bsxfun</code> can apply arbitrary operators. As a side note, it is very interesting to see that <code>bsxfun</code> is as fast as the BLAS outer product. And BLAS is usually considered to deliver <strong>the</strong> performance..</p> <p><strong>Edit</strong> Thanks to Dan's comment, here is a great <a href="http://blogs.mathworks.com/loren/2008/08/04/comparing-repmat-and-bsxfun-performance/" rel="nofollow noreferrer">article by Loren</a> discussing exactly that.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload