How to sum different cells of cell array

2 views (last 30 days)
federico nutarelli
federico nutarelli on 2 Mar 2021
Commented: Rik on 2 Mar 2021
Hi all,
I have the following problem.
I have a cell array (2x100) where each entry is a 11x74 table. What I would llike to do is to make the mean over those 100 tables of each value.
So if for instance I have a cell array (2x2) of say 2x3 matrices:
[1,2,3;4,5,6] [3,24,35;46,58,69]
[10,2,3;24,85,6] [11,22,33;54,15,16]
I would like to end up with the mean by row of each matrix so:
[(1+3)/2, (2+24)/2,(35+3)/2;(46+4)/2,58+5)/2,(69+6)/2]
[(10+11)/2,(2+22)/2,(3+33)/2;(24+54)/2,(85+15)/2,(6+16)/2]
Is there a way to do that?
Thank you

Answers (2)

Rik
Rik on 2 Mar 2021
Something like this should work:
data={[1,2,3;4,5,6],[3,24,35;46,58,69];
[10,2,3;24,85,6],[11,22,33;54,15,16]};
data=permute(data,[3 4 1 2]);
data=cell2mat(data);
data=mean(data,4)
data =
data(:,:,1) = 2.0000 13.0000 19.0000 25.0000 31.5000 37.5000 data(:,:,2) = 10.5000 12.0000 18.0000 39.0000 50.0000 11.0000
You can reshape this output as needed.
  2 Comments
federico nutarelli
federico nutarelli on 2 Mar 2021
Edited: federico nutarelli on 2 Mar 2021
Thank you for the answer @Rik. The problem is that my cell array is quite big. It i actually a (2x100) array. Can I usse prmute in this case too?
Also the following error arrise when using cell2mat:
Error using cat
Dimensions of arrays being concatenated are not consistent.
Error in cell2mat (line 118)
ct{mref{:}} = cat(cdim+1,c{mref{:},:});
I tried to delete empty cells but nothing changes:
data = Po1.Po(~cellfun('isempty',Po1.Po));
Rik
Rik on 2 Mar 2021
You could fill the empty arrays with NaN and use the 'omitnan' flag. 2x100 is not big. It is too cumbersome to display in text easily, but Matlab has a max array size far exceeding 2*100*11*74.
If the order of your cells doesn't matter, you could also use cat(3,data{:}) (assuming you have already removed all empty cells and the remainder has the same size.

Sign in to comment.


Star Strider
Star Strider on 2 Mar 2021
I would do something like this:
C = {[1,2,3;4,5,6] [3,24,35;46,58,69]
[10,2,3;24,85,6] [11,22,33;54,15,16]};
cat3 = zeros(size(C{1},1),size(C{1},2),size(C,2));
for k1 = 1:size(C,1)
for k2 = 1:size(C,2)
cat3(:,:,k2) = C{k1,k2};
end
cat3_mean{k1,:} = mean(cat3,3)
end
cat3_mean{:} % Display Results
With the number of your matrices, two nested loops is likely the only possible solution. The cat function can do this, however it requires that the matrices to be concatenated be listed separately, and that does not appear to be possible here.

Categories

Find more on Cell Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!