You can apply a function to every item in a vector by saying, for example, v + 1
, or you can use the function arrayfun
. How can I do it for every row/column of a matrix without using a for loop?
Many built-in operations like sum
and prod
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.
If that's not a viable option, one way to do it is to collect the rows or columns into cells using mat2cell
or num2cell
, then use cellfun
to operate on the resulting cell array.
As an example, let's say you want to sum the columns of a matrix M
. You can do this simply using sum
:
M = magic(10); %# A 10-by-10 matrix
columnSums = sum(M, 1); %# A 1-by-10 vector of sums for each column
And here is how you would do this using the more complicated num2cell
/cellfun
option:
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