MATLAB: Compute average in different columns of cell arrays without considering 0 values

mean cell

I have a cell array of 30 arrays. Each cell in it is a matrix of thousands rows and let's say several columns.
With a simple example, my cell is C and C{1,1} contains a matrix of single double values like this
C{1,1}=[1 4 5
2 56 6
3 0 0]
C{2,1}=[1 0 0
2 6 11
3 0 0]
Also I want to get the mean of all non zeros elements in the 2nd columns in all the cell matrices
If I do
mean(C{1,1}(:,2)) %mean of 2nd column in first cell matrix
but this also includes values where 2nd column is 0 so to remove zero values I did in 3 steps
A=C{1,1};
B=A(:,2)>0;
mean(A(B,2));
or in a single line
mean(C{1,1}(C{1,1}(:,2)>0,2))
So far, this is ok and gives me the average of a the second column in the first cell matrix but then when I wanted to get at once all the averages of the cell matrices and compute its means later with
Averages(:)= mean(C{:,1}(:,2))
but I get an error. I am not removing the zeros here just for the line to be more clear. My problem is how to use the : with the cell matrices. With a for loop, I can do it like this
Averages=zeros(30,1);
for ii=1:30
Averages(ii)=mean(C{ii,1}(C{ii,1}(:,2)>0,2));
end
AvgC=mean(Averages);
But is there a way to do it without for. In other words how can access to the all cells 2nd column at once?

Best Answer

z = cat(3,C{:});
x = squeeze(z(:,2,:));
out = (sum(x)./sum(x~=0))';