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 件のコメント
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
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
2016 年 4 月 19 日
The mean will take into account zeros, while Andrei's code does what you asked and does not include zeros.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!