MATLAB: Mean of Cells of Cells

cells

So I have cell arrays that contain other cells The structure looks like this:
Cell{X} always contains 3 sub-cells, the first sub-cell always contains a 16×107 matrix, the second one a 16×47 matrix and the third one a 16×147 matrix. These are matrices with those dimensions. I want to take the (nan)mean of all same-sized matrices, in some way that is the intuitive equivalent of this: nanmean(Cell{1:end}{1}), nanmean(Cell{1:end}{2}), nanmean(Cell{1:end}{3}), etc. The mean should be taken along the 1st dimension so I end up with with 3 mean matrices, one 16×107, one 16×47, and one 16×147.
Obviously the above ways don't work ('Bad cell reference operation'). How can I do this without looping through everything and adding them up one by one?
To Clarify:
My data:
Cell_1(cell_1(Matrix),cell_2(Matrix),cell_3(Matrix))
Cell_2(cell_1(Matrix),cell_2(Matrix),cell_3(Matrix))
Cell_3(cell_1(Matrix),cell_2(Matrix),cell_3(Matrix))
Cell_4(cell_1(Matrix),cell_2(Matrix),cell_3(Matrix))
I want to get 3 mean matrices, one of all cell_1(Matrix), one of all cell_2(Matrix), and one of all cell_3(Matrix), where the 3 mean matrices are of size cell_1(Matrix), cell_2(Matrix), and cell_3(Matrix). I do not want to take means along the dimensions within a given cell(Matrix), but along the dimensions of Cell, NOT cell.

Best Answer

Try this
Edit
%-----------Your array--------------------------------------------------
Y1={num2cell(rand(16,107)),num2cell(rand(16,47)),num2cell(rand(16,147))};
Y2={num2cell(rand(16,107)),num2cell(rand(16,47)),num2cell(rand(16,147))};
Y3={num2cell(rand(16,107)),num2cell(rand(16,47)),num2cell(rand(16,147))};
Y4={num2cell(rand(16,107)),num2cell(rand(16,47)),num2cell(rand(16,147))};
Ycell={Y1,Y2,Y3,Y4}
%----------------Your code------------------------------------------------
n=numel(Ycell);
m=numel(Ycell{1});
M=cell(n,m);
for p=1:m
for k=1:n
M{k,p}=cell2mat(Ycell{k}{p});
end
[ii,jj]=size(M{k,p});
a=cell2mat(M(1:n,p));
b=reshape(a',jj,ii,[]);
out{p}=nanmean(b,3)';
end
out