valar
valar

Reputation: 31

How to sum up all the arrays (identical sizes) inside a cell array?

For instance, I have the following cell array:

a = [1,2,3; 1,5,8; 6,5,0; 0,0,2];
A = cell(3,4);
for i = 1:3
    for j = 1:4
        A{i,j} = (j-i)*a;
    end
end

How could I sum up all the elements i.e. A{1,1} + A{1,2} + ... + A{3,4}?

Upvotes: 3

Views: 102

Answers (1)

Sardar Usama
Sardar Usama

Reputation: 19689

Concatenate the matrices in each cell along the third dimension and then sum along the third dimension.

TD = cat(3, A{:});    %Converting the cell array to a 3D array
result = sum(TD, 3);  %Summation of 3D slices

Upvotes: 8

Related Questions