tags:

views:

434

answers:

1

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

+5  A: 

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
gnovice
I would test performance of this approach for any particular case against simple for-loop, which might be faster then converting a matrix to cell array. Use tic/tac wrap to test.
yuk
@yuk: I think you meant "tic/toc". ;)
gnovice
@gnovice: Oops, of course! Just something ticking... :)
yuk

related questions