user3190506
user3190506

Reputation: 23

Summation of matrices

I want to sum together each cell in the same position for each matrix. I have k amount of (i,j) matrices stored in MATLAB as (i,j,k) and I want to create one matrix which is the sum of all them - however the MATLAB command sums together every value in each column whereas I want to sum together each cell in the same position from each matrix.

 1  3  4       3  4  0        2  4  4
 0  3  1       2  7  8        0  3  1 
 9  0  2       0  1  2        1  2  3

I want to create a matrix that is:

 1+3+2   3+4+4    4+0+4
 0+2+1   3+7+3    1+8+1
 9+0+1   0+1+2    2+2+3

=

6   11  8
3   13  10
10  3   7 

Upvotes: 1

Views: 129

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112679

Use a second input to sum specifying the dimension along which to sum (in your case, 3):

>> A(:,:,1) = [ 1  3  4      
                0  3  1       
                9  0  2 ];
>> A(:,:,2) = [ 3  4  0        
                2  7  8        
                0  1  2 ];   
>> A(:,:,3) = [ 2  4  4
                0  3  1 
                1  2  3 ];

>> sum(A,3)
ans =
     6    11     8
     2    13    10
    10     3     7

Upvotes: 3

Related Questions