MATLAB: The sum of stacked matrices

3daddmatricesmatrixstacksum

I have a 3-d matrix and I want to find the sum so that every element in the sum matrix is the sum of all the elements in that corresponding i,j location. I know that sounds confusing probably so for example:
>> A=zeros(3,3,3);
>> A(:,:,1)=[1 1 1; 1 0 1; 0 0 0];
>> A(:,:,2)=[1 1 1; 0 0 1; 0 1 0];
>> A(:,:,3)=[1 0 1; 0 1 0; 0 1 0];
Would give me a sum matrix that would be:
[ 3 2 3
1 1 2
0 2 0 ]
I realize I could reshape the matrices into a vector, sum them, and then reshape them back into the matrix, and that I could use for loops, but both of those seem over complicated and I would be doing this with a pretty large amount of data so speed is ideal 🙂
Thanks in advance!
-Shaun

Best Answer

sum(A,3)
Roger Stafford