% Do mean on all elements of a cell array
% s = cellmean(cellarray,doNaNmean)

function s = cellmean(cellarray,doNaNmean)

    if nargin<2 || isempty(doNaNmean)
        doNaNmean = 0;
    end
    
if length(size(cellarray))>2
   error('This only works for cell arrays up to 2D');
end

if iscell(cellarray{1,1})
    for i=1:size(cellarray,1)
        for j=1:size(cellarray,2)
            s{i,j} = cellmean(cellarray{i,j});
        end
    end
    return;
end

for i=1:size(cellarray,1)
    for j=1:size(cellarray,2)
        if doNaNmean
            themean = nanmean(cellarray{i,j});
        else
            themean = mean(cellarray{i,j});
        end
        if length(themean)==1
            s(i,j) = themean;
        else
            s{i,j} = themean;
        end
    end
end
