matlab - Summing a cell array? -
i have function takes in number of arguments cell array
function sumthese(varargin) subtotals = cellfun(@sum, varargin); total = sum(subtotals); disp(total) end this works arrays , numbers, except have square matrix doesn't. it'll tell me:
non-scalar in uniform output, set 'uniformoutput' false.
however if set 'uniformoutput' false, error now:
undefined function or method 'sum' input arguments of type 'cell
how approach this?
change function @sum in cellfun
subtotals = cellfun( @(x) sum(x(:)), varargin ); why?
becuase output of sum, when applied matrix no longer scalar turns subtotals cell array of scalars , vectors, instead of 1d vector.
use debugger see difference.
ps,
did know cellfun not better simple loop.
edit:
solution using for loop:
total = 0; ii = 1:numel(varargin) total = total + sum( varargin{ii}(:) ); end
Comments
Post a Comment