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

조회 수: 3 (최근 30일)
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
etudiant_is
etudiant_is 2016년 4월 19일
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 2016년 4월 19일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Andrei Bobrov
Andrei Bobrov 2016년 4월 19일
편집: Andrei Bobrov 2016년 4월 19일
z = cat(3,C{:});
x = squeeze(z(:,2,:));
out = (sum(x)./sum(x~=0))';
  댓글 수: 4
Image Analyst
Image Analyst 2016년 4월 19일
The mean will take into account zeros, while Andrei's code does what you asked and does not include zeros.
etudiant_is
etudiant_is 2016년 4월 19일
ok, that was it. Thanks a lot for both of you.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by