Matthias Pospiech
Matthias Pospiech

Reputation: 3488

create sum of cell matrices

I want to have the sum of all matrices stored in a cell array. Currently I do this

StackSummImage = zeros(size(imageList{1}));
for k = 1:stackSize
     StackSummImage = StackSummImage + imageList{k};
end

But I would rather want to write it in a single line if possible.

Upvotes: 3

Views: 4050

Answers (2)

Chris Taylor
Chris Taylor

Reputation: 47402

If each of the N images is K x K, you can use cat to concatenate all the images into a K x K x N array, and then sum it along the third dimension:

>> imageList = {[1 2; 3 4], [5 6; 7 8], [9 10; 11 12]};
>> stackSummImage = sum(cat(3,imageList{:}),3)
ans =
15    18
21    24

Edit: You mentioned in the comments that you can't create a single array, because of memory limits. Below is the memory usage profile when I first allocate a 1500x1500x1500 array of doubles (which takes around 30 GB) and deallocate it, followed by allocating a cell array of 1500 arrays, each of which is a 1500x1500 double array. As you can see, the total memory usage is the same in both cases.

enter image description here

Upvotes: 4

PearsonArtPhoto
PearsonArtPhoto

Reputation: 39748

This line should do:

StackSummImage = sum([imageList{:}])

Upvotes: -1

Related Questions