Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Many built-in operations like <a href="http://www.mathworks.com/help/matlab/ref/sum.html" rel="noreferrer"><code>sum</code></a> and <a href="http://www.mathworks.com/help/matlab/ref/prod.html" rel="noreferrer"><code>prod</code></a> are already able to operate across rows or columns, so you may be able to refactor the function you are applying to take advantage of this.</p> <p>If that's not a viable option, one way to do it is to collect the rows or columns into cells using <a href="http://www.mathworks.com/help/matlab/ref/mat2cell.html" rel="noreferrer"><code>mat2cell</code></a> or <a href="http://www.mathworks.com/help/matlab/ref/num2cell.html" rel="noreferrer"><code>num2cell</code></a>, then use <a href="http://www.mathworks.com/help/matlab/ref/cellfun.html" rel="noreferrer"><code>cellfun</code></a> to operate on the resulting cell array.</p> <p>As an example, let's say you want to sum the columns of a matrix <code>M</code>. You can do this simply using <a href="http://www.mathworks.com/help/matlab/ref/sum.html" rel="noreferrer"><code>sum</code></a>:</p> <pre><code>M = magic(10); %# A 10-by-10 matrix columnSums = sum(M, 1); %# A 1-by-10 vector of sums for each column </code></pre> <p>And here is how you would do this using the more complicated <a href="http://www.mathworks.com/help/matlab/ref/num2cell.html" rel="noreferrer"><code>num2cell</code></a>/<a href="http://www.mathworks.com/help/matlab/ref/cellfun.html" rel="noreferrer"><code>cellfun</code></a> option:</p> <pre><code>M = magic(10); %# A 10-by-10 matrix C = num2cell(M, 1); %# Collect the columns into cells columnSums = cellfun(@sum, C); %# A 1-by-10 vector of sums for each cell </code></pre>
 

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