rawr rang
rawr rang

Reputation: 973

Summing a cell array?

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?

Upvotes: 1

Views: 2691

Answers (1)

Shai
Shai

Reputation: 114786

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

Upvotes: 3

Related Questions