Hi all,
you can apply function to every item in a vector by saying v .+ 1, or you can use arrayfun, any one have any suggestions on how to do it for every row/column of a matrix without using for loop?
thank you very much!
Jason
Hi all,
you can apply function to every item in a vector by saying v .+ 1, or you can use arrayfun, any one have any suggestions on how to do it for every row/column of a matrix without using for loop?
thank you very much!
Jason
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); %# 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