MATLAB: How to use ‘rowfun’ to calculate stats for rows in a table

argumentsinputMATLABrowfunstatisticsvararginvarfun

How can I use 'rowfun' to calculate basic stats for rows in a table ?
If I try to use a function like 'sum' or 'mean' with 'rowfun' it returns an error message. For example:
>> aaa = array2table(magic(7))
>> foo = rowfun(@sum, aaa)
Error using table/rowfun>dfltErrHandler (line 311)
Applying the function 'sum' to the 1st row of aaa generated the following error:
Too many input arguments.
Error in table/rowfun>@(s,varargin)dfltErrHandler(grouped,funName,s,varargin{:}) (line 195)
errHandler = @(s,varargin) dfltErrHandler(grouped,funName,s,varargin{:});
Error in table/rowfun (line 218)
[b_data{i,:}] = errHandler(struct('identifier',ME.identifier, 'message',ME.message,
'index',i),inArgs{:});

Best Answer

'rowfun' returns error messages because it is trying to pass each element for a row as a separate input argument.
In this case, 'sum' expects one vector containing all inputs.
To make 'rowfun' pass the values in each row as a single input, set the 'SeparateInputs' input argument to false:
>> aaa = array2table(magic(7));
>> foo = rowfun(@sum, aaa, 'SeparateInputs', false)
foo =
Var1
____
175
175
175
175
175
175
175
An alternate solution is to use varargin in the function handle as below:
>> aaa = array2table(magic(7));
>> foo = rowfun(@(varargin)sum([varargin{:}]), aaa);