Summing arrays inside cells

94 views Asked by At

I have a code in MATLAB that produces 1000 x 1000 arrays in a loops that runs ten times; to try and save all these loops, I commit these arrays to a cell; Now I have a cell 1 x 10 cell nalled PL, each element being a 1000 x 1000 array; I want to sum these in the easiest way possible, so that I get one 1000 x 1000 output. I've tried using

PLtot = cellfun(@sum,PL, 'UniformOutput',false);

but this does not work at all for me - any ideas? I'm sure this should be simple but having a headache doing it!

3

There are 3 answers

2
Vuwox On BEST ANSWER

Instead of storing your array into cellarray.

Just add an extra dimension to your initial array. Always preallocate the size to the array.

PL = zeros(1000,1000,10);

So when you want to access to each image it's easier. And for the sum just do :

PLtot = sum(PL,3);
0
Rich Nicholson On

The following works for me:

PLtot =  sum(cat(3,PL{:}),3);

It concatenates the arrays in the 3rd dimension and then simply sums along this dimension.

0
yuk On

Your code is not wrong, so you shouldn't get an error. I think you just aren't satisfied with the result.

cellfun returns you the cell array of column-wise-sum vectors, each one is the result of applying sum function to individual cell. You just need to transform it to a matrix.

PLtotcell = cellfun(@sum,PL, 'UniformOutput',false); % 
PLtot = cell2mat(PLtotcell');

I have to say that this is not the most efficient way in your case. Check other answers for better performance. I just wanted you to understand how your code works.