Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You may want the more obscure Matlab function <a href="http://www.mathworks.com/help/matlab/ref/bsxfun.html" rel="noreferrer">bsxfun</a>. From the Matlab documentation, bsxfun "applies the element-by-element binary operation specified by the function handle fun to arrays A and B, with singleton expansion enabled."</p> <p>@gnovice stated above that sum and other basic functions already operate on the first non-singleton dimension (i.e., rows if there's more than one row, columns if there's only one row, or higher dimensions if the lower dimensions all have size==1). However, bsxfun works for any function, including (and especially) user-defined functions.</p> <p>For example, let's say you have a matrix A and a row vector B. E.g., let's say:</p> <pre><code>A = [1 2 3; 4 5 6; 7 8 9] B = [0 1 2] </code></pre> <p>You want a function power_by_col which returns in a vector C all the elements in A to the power of the corresponding column of B.</p> <p>From the above example, C is a 3x3 matrix:</p> <pre><code>C = [1^0 2^1 3^2; 4^0 5^1 6^2; 7^0 8^1 9^2] </code></pre> <p>i.e.,</p> <pre><code>C = [1 2 9; 1 5 36; 1 8 81] </code></pre> <p>You could do this the brute force way using repmat:</p> <pre><code>C = A.^repmat(B, size(A, 1), 1) </code></pre> <p>Or you could do this the classy way using bsxfun, which internally takes care of the repmat step:</p> <pre><code>C = bsxfun(@(x,y) x.^y, A, B) </code></pre> <p>So bsxfun saves you some steps (you don't need to explicitly calculate the dimensions of A). However, in some informal tests of mine, it turns out that repmat is roughly twice as fast if the function to be applied (like my power function, above) is simple. So you'll need to choose whether you want simplicity or speed.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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