for - matlab rowfun
How can I apply a function to every row/column of a matrix in MATLAB? (8)
The accepted answer seems to be to convert to cells first and then use
cellfun to operate over all of the cells. I do not know the specific application, but in general I would think using
bsxfun to operate over the matrix would be more efficient. Basically
bsxfun applies an operation element-by-element across two arrays. So if you wanted to multiply each item in an
n x 1 vector by each item in an
m x 1 vector to get an
n x m array, you could use:
vec1 = [ stuff ]; % n x 1 vector vec2 = [ stuff ]; $ m x 1 vector result = bsxfun('times', vec1.', vec2);
This will give you matrix called
result wherein the (i,j) entry will be the ith element of
vec1 multiplied by the jth element of
You can use
bsxfun for all sorts of built-in functions, and you can declare your own. The documentation has a list of many built-in functions, but basically you can name any function that accepts two arrays (vector or matrix) as arguments and get it to work.
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?
Adding to the evolving nature of the answer to this question, starting with r2016b, MATLAB will implicitly expand singleton dimensions, removing the need for
bsxfun in many cases.
From the r2016b release notes:
Implicit Expansion: Apply element-wise operations and functions to arrays with automatic expansion of dimensions of length 1
Implicit expansion is a generalization of scalar expansion. With scalar expansion, a scalar expands to be the same size as another array to facilitate element-wise operations. With implicit expansion, the element-wise operators and functions listed here can implicitly expand their inputs to be the same size, as long as the arrays have compatible sizes. Two arrays have compatible sizes if, for every dimension, the dimension sizes of the inputs are either the same or one of them is 1. See Compatible Array Sizes for Basic Operations and Array vs. Matrix Operations for more information.
Element-wise arithmetic operators — +, -, .*, .^, ./, .\ Relational operators — <, <=, >, >=, ==, ~= Logical operators — &, |, xor Bit-wise functions — bitand, bitor, bitxor Elementary math functions — max, min, mod, rem, hypot, atan2, atan2d
For example, you can calculate the mean of each column in a matrix A, and then subtract the vector of mean values from each column with A - mean(A).
Previously, this functionality was available via the bsxfun function. It is now recommended that you replace most uses of bsxfun with direct calls to the functions and operators that support implicit expansion. Compared to using bsxfun, implicit expansion offers faster speed, better memory usage, and improved readability of code.
For completeness/interest I'd like to add that matlab does have a function that allows you to operate on data per-row rather than per-element. It is called
rowfun (http://www.mathworks.se/help/matlab/ref/rowfun.html), but the only "problem" is that it operates on tables (http://www.mathworks.se/help/matlab/ref/table.html) rather than matrices.
I can't comment on how efficient this is, but here's a solution:
applyToGivenRow = @(func, matrix) @(row) func(matrix(row, :)) applyToRows = @(func, matrix) arrayfun(applyToGivenRow(func, matrix), 1:size(matrix,1))' % Example myMx = [1 2 3; 4 5 6; 7 8 9]; myFunc = @sum; applyToRows(myFunc, myMx)
None of the above answers worked "out of the box" for me, however, the following function, obtained by copying the ideas of the other answers works:
apply_func_2_cols = @(f,M) cell2mat(cellfun(f,num2cell(M,1), 'UniformOutput',0));
It takes a function
f and applies it to every column of the matrix
So for example:
f = @(v) [0 1;1 0]*v + [0 0.1]'; apply_func_2_cols(f,[0 0 1 1;0 1 0 1]) ans = 0.00000 1.00000 0.00000 1.00000 0.10000 0.10000 1.10000 1.10000
Stumbled upon this question/answer while seeking how to compute the row sums of a matrix.
I would just like to add that Matlab's SUM function actually has support for summing for a given dimension, i.e a standard matrix with two dimensions.
So to calculate the column sums do:
colsum = sum(M) % or sum(M, 1)
and for the row sums, simply do
rowsum = sum(M, 2)
My bet is that this is faster than both programming a for loop and converting to cells :)
All this can be found in the matlab help for SUM.
You may want the more obscure Matlab function bsxfun. From the Matlab documentation, bsxfun "applies the element-by-element binary operation specified by the function handle fun to arrays A and B, with singleton expansion enabled."
@gnovice stated above that sum and other basic functions already operate on the first non-singleton dimension (i.e., rows if there's more than one row, columns if there's only one row, or higher dimensions if the lower dimensions all have size==1). However, bsxfun works for any function, including (and especially) user-defined functions.
For example, let's say you have a matrix A and a row vector B. E.g., let's say:
A = [1 2 3; 4 5 6; 7 8 9] B = [0 1 2]
You want a function power_by_col which returns in a vector C all the elements in A to the power of the corresponding column of B.
From the above example, C is a 3x3 matrix:
C = [1^0 2^1 3^2; 4^0 5^1 6^2; 7^0 8^1 9^2]
C = [1 2 9; 1 5 36; 1 8 81]
You could do this the brute force way using repmat:
C = A.^repmat(B, size(A, 1), 1)
Or you could do this the classy way using bsxfun, which internally takes care of the repmat step:
C = bsxfun(@(x,y) x.^y, A, B)
So bsxfun saves you some steps (you don't need to explicitly calculate the dimensions of A). However, in some informal tests of mine, it turns out that repmat is roughly twice as fast if the function to be applied (like my power function, above) is simple. So you'll need to choose whether you want simplicity or speed.
if you know the length of your rows you can make something like this:
a=rand(9,3); b=rand(9,3); arrayfun(@(x1,x2,y1,y2,z1,z2) line([x1,x2],[y1,y2],[z1,z2]) , a(:,1),b(:,1),a(:,2),b(:,2),a(:,3),b(:,3) )