Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove diagonal element square from a matrix?

Tags:

r

matrix

We can use diag() to remove diagonal elements of a matrix, but what if we want to remove a diagonal square of elements? Like in a 6x6 matrix, I want to remove 2x2 squares in the diagonal. It looks very basic, but how to do that in r?

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]   23   98   12   98   32   99
[2,]   54   11   13   02   31   78
[3,]   25   85   15   09   46   87
[4,]   98   98   16   17   45   48
[5,]   88   00   68   99   89   89
[6,]   05   33   66   12   14   78

and I want to set the diagonal square to NA

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]   NA   NA   12   98   32   99
[2,]   NA   NA   13   02   31   78
[3,]   25   85   NA   NA   46   87
[4,]   98   98   NA   NA   45   48
[5,]   88   00   68   99   NA   NA
[6,]   05   33   66   12   NA   NA

remove all the NAs and then we combine the columns

     [,1] [,2] [,3] [,4]
 [1,]  12   98   32   99
 [2,]  13   02   31   78
 [3,]  25   85   46   87
 [4,]  98   98   45   48
 [5,]  88   00   68   99
 [6,]  05   33   66   12
like image 537
user3697665 Avatar asked Feb 09 '23 16:02

user3697665


2 Answers

I expect there's a more elegant way to do this, but here's one way:

# Create a matrix
mat = matrix(1:36, nrow=6)

# Set block diagonal elements to NA
for (i in seq(1, nrow(mat), 2)) {
  mat[i:(i+1),i:(i+1)] = NA
}

# Reform the matrix with the NA values excluded
matrix(mat[!is.na(mat)], nrow=nrow(mat)-2)
like image 127
eipi10 Avatar answered Feb 11 '23 07:02

eipi10


You could use the Kronecker product to quickly construct a block diagonal matrix indicating which elements are to be kept and which are to be removed.

## An example matrix
set.seed(1)
m <- matrix(sample(1:100, 36), ncol=6)

## Construct a logical block diagonal matrix, then use it to remove blocks along diagonal
ii <- !kronecker(diag(1, nrow(m)/2), matrix(1, ncol=2, nrow=2))
matrix(m[ii], ncol = ncol(m)-2)
##      [,1] [,2] [,3] [,4]
## [1,]   57   19   32    1
## [2,]   89   16   63   28
## [3,]   20   61   51   87
## [4,]   86   34   10   42
## [5,]   58   88   21   70
## [6,]    6   83   29   13
like image 41
Josh O'Brien Avatar answered Feb 11 '23 07:02

Josh O'Brien