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?
You can apply a function to every item in a vector by saying, for
Share
Many built-in operations like
sumandprodare 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
mat2cellornum2cell, then usecellfunto 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 usingsum:And here is how you would do this using the more complicated
num2cell/cellfunoption: