Roma
Roma

Reputation: 49

Sum of a cell array along the column

I have a cell array like <1x74 cell> and each element of the cell is a matrix of 4 X 4. How do I sum up so that I have a final matrix of 4 X 4. I initially did in the following manner:

Total = In{1,1}+In{1,2}+In{1,3}+In{1,4}+In{1,5}+In{1,6}+In{1,7}+In{1,8}+In{1,9}+In{1,10}+.....In{1,74};

Upvotes: 0

Views: 85

Answers (2)

Daniel
Daniel

Reputation: 36710

Assuming you create a 74x4x4 3D matrix instead of a cell array, you can simply use sum

Total=sum(In);

It will result in a 1x4x4 matrix, to get a 4x4 matrix use shiftdim

Total=shiftdim(sum(In))

Upvotes: 0

Davood
Davood

Reputation: 1566

Total = zeros(2,2);

for i=1:size(In,2)
    Total = Total+In{1,i};
end
display('This is the result: ')
Total

As you mentioned in the comments, if you don't want to define Total in prior, do this

for i=1:size(In,2)
    if i~=1 
    Total = Total + In{1,i}; % executes for numbers equal or larger than 2
    else
    Total = In{1,i}; %executes on i=1
    end
end

Upvotes: 2

Related Questions