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

3 visualizaciones (últimos 30 días)
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?
  5 comentarios
etudiant_is
etudiant_is el 19 de Abr. de 2016
Actually, in this example I have cell arrays of single elements but I have others cells where each element is of different type (matrices, single elements, etc). So I don't think I can do it without cells for these cases. What should I use instead of cells then?
Image Analyst
Image Analyst el 19 de Abr. de 2016
If each column of the cell array is of the same type, like column 1 is all strings, and column 2 is all scalars, then you can use a "table" variable, as long as you have R2013b or later.

Iniciar sesión para comentar.

Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 19 de Abr. de 2016
Editada: Andrei Bobrov el 19 de Abr. de 2016
z = cat(3,C{:});
x = squeeze(z(:,2,:));
out = (sum(x)./sum(x~=0))';
  4 comentarios
Image Analyst
Image Analyst el 19 de Abr. de 2016
The mean will take into account zeros, while Andrei's code does what you asked and does not include zeros.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by