Sure we have array­fun, but it applies a func­tion every ele­ment of a matrix. What if we want to com­pute the sum over each row or col­umn for example ?

The trick that I’m pre­sent­ing here lies in the use of the num2cell function.

In the exam­ple below, we add a 1x4 vec­tor to every row of a matrix A.

>> A = magic(4)
A =
 
    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1
 
>> y = [1 2 3 4];
>> B = cellfun(@(x)(x + y), num2cell(A, 2), ‘Uni­for­mOut­put’, false)
 
B = 
 
    [1x4 double]
    [1x4 double]
    [1x4 double]
    [1x4 double]
 
>> cell2mat(B)
 
ans =
 
    17     4     6    17
     6    13    13    12
    10     9     9    16
     5    16    18     5

If we wanted to do a sim­i­lar oper­a­tion but this time over the columns, we would write num2cell(A, 1) : “1” instead of “2”.