1

I have a function that takes in any number of arguments into a cell array

function sumThese(varargin)

subtotals = cellfun(@sum, varargin);
total = sum(subtotals);

disp(total)
end 

This works for arrays and numbers, except as soon as I have a square matrix it doesn't. It'll tell me:

Non-scalar in Uniform output, set 'UniformOutput' to false.

However if I set 'uniformoutput' to false, I get this error now:

Undefined function or method 'sum' for input arguments of type 'cell

How to approach this?

Shai
  • 111,146
  • 38
  • 238
  • 371
rawr rang
  • 763
  • 2
  • 7
  • 24

1 Answers1

3

Change the function @sum in the cellfun

subtotals = cellfun( @(x) sum(x(:)), varargin );

Why?
becuase the output of sum, when applied to a matrix is no longer a scalar what turns subtotals into a cell array of scalars and vectors, instead of a 1D vector.

Use debugger to see the difference.

PS,
Did you know that cellfun is not always better than a simple loop.

EDIT:
A solution using for loop:

total = 0;
for ii = 1:numel(varargin)
    total = total + sum( varargin{ii}(:) );
end
Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371
  • Thanks that works! Can you give me a hint on how to loop through it? – rawr rang May 20 '13 at 05:23
  • One follow up, what if one of the arguments is a cell array? Then sum won't work on it since it is type cell... – rawr rang May 20 '13 at 05:39
  • 1
    @rawrrang and what if there are `NaN`s in some of the cells? and what if there are strings/chars? You should know your inputs... If the inputs are very complicated you should replace the simple `sum` function with something more sophisticated that you'll write that can handle all these special cases... – Shai May 20 '13 at 05:42