Compute average in different columns of cell arrays without considering 0 values
2 views (last 30 days)
Show older comments
etudiant_is
on 19 Apr 2016
Commented: Image Analyst
on 19 Apr 2016
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 Comments
Image Analyst
on 19 Apr 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.
Accepted Answer
Andrei Bobrov
on 19 Apr 2016
Edited: Andrei Bobrov
on 19 Apr 2016
z = cat(3,C{:});
x = squeeze(z(:,2,:));
out = (sum(x)./sum(x~=0))';
4 Comments
Image Analyst
on 19 Apr 2016
The mean will take into account zeros, while Andrei's code does what you asked and does not include zeros.
More Answers (0)
See Also
Categories
Find more on Genetic Algorithm in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!