user191919
user191919

Reputation: 754

Summing Matrices in the Diagonal - MatLab

Is there any easy command/code to sum the block submatrices in the diagonal of an encompassing matrix? An example:

A = [A11 A12;A21 A22]

I would like to obtain A11+A22, where Aij are NxK block matrices.

Thanks.

Upvotes: 2

Views: 250

Answers (2)

Divakar
Divakar

Reputation: 221524

Given

  • D as number of diagonal matrices
  • N and K as size parameters of each block

The listed code next would be a generic code to achieve the goals set in the problem -

start_block = bsxfun(@plus,[1:N]',[0:K-1]*D*N)     %//'# Starting block indices
blks = A(bsxfun(@plus,start_block(:),[0:D-1]*(D*N*K + N)))%// Blocks in columns
out = reshape(sum(blks,2),N,K) %// Sum blks across columns and reshape into a 
                               %// N x K array for the final output

Sample run with D = 4, N = 4 & K = 3 -

A =
     6     9     9     2     7     6     2     9     1     1     4     2
     4     5     5     3     7     4     9     8     8     6     6     2
     3     3     7     1     6     9     3     7     9     9     7     3
     5     7     2     9     4     3     9     8     1     4     6     7
     4     7     9     6     4     6     3     4     9     4     5     8
     4     7     5     9     8     6     4     6     1     9     6     7
     6     7     7     2     3     4     1     6     7     9     5     1
     7     1     1     9     8     2     6     5     8     7     1     8
     4     7     8     8     8     1     2     3     5     9     7     9
     4     5     7     6     8     4     1     3     8     7     9     7
     2     2     2     4     5     2     7     5     9     4     4     1
     1     1     5     3     6     7     4     3     6     6     9     4
     3     8     3     7     9     4     6     8     2     3     4     7
     3     2     5     3     4     8     4     9     2     3     8     7
     6     2     4     1     1     7     6     1     2     7     5     3
     9     6     4     7     8     6     1     5     1     5     4     3
blks =
     6     6     2     3
     4     9     1     3
     3     2     7     7
     5     9     4     5
     9     4     3     4
     5     8     3     8
     3     3     5     5
     7     8     3     4
     9     6     5     7
     5     6     8     7
     7     4     9     3
     2     2     6     3
out =
    17    20    27
    17    24    26
    19    16    23
    23    22    13

Verify the output of sample run -

>> A(1:4,1:3) + A(5:8,4:6) + A(9:12,7:9) + A(13:16,10:12)
ans =
    17    20    27
    17    24    26
    19    16    23
    23    22    13

Upvotes: 1

Daniel
Daniel

Reputation: 36710

That's just some matrix indexing:

N=size(A,1)/2;
K=size(A,2)/2;
E=A(1:N,1:K)+A(N+1:end,K+1:end)

I recommend to read the documentation pages about matrix indexing and the colon operator.

Upvotes: 2

Related Questions