Home > Blockchain >  Matrix of 10x10 with the same values on principal diagonal and anti-diagonal are the same and for th
Matrix of 10x10 with the same values on principal diagonal and anti-diagonal are the same and for th

Time:05-28

I would create in R a square matrix where the values on main diagonal and anti-diagonal is the same. It's 2. The otherwise value is 0

CodePudding user response:

Here is a simple way :

a <- matrix(0 , 10,10)
diag(a) <- 2
a <- data.frame(a)
a <- as.matrix(data.frame(lapply(a , rev)))
diag(a) <- 2
colnames(a) <- NULL
a
#>       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#>  [1,]    2    0    0    0    0    0    0    0    0     2
#>  [2,]    0    2    0    0    0    0    0    0    2     0
#>  [3,]    0    0    2    0    0    0    0    2    0     0
#>  [4,]    0    0    0    2    0    0    2    0    0     0
#>  [5,]    0    0    0    0    2    2    0    0    0     0
#>  [6,]    0    0    0    0    2    2    0    0    0     0
#>  [7,]    0    0    0    2    0    0    2    0    0     0
#>  [8,]    0    0    2    0    0    0    0    2    0     0
#>  [9,]    0    2    0    0    0    0    0    0    2     0
#> [10,]    2    0    0    0    0    0    0    0    0     2

Created on 2022-05-28 by the reprex package (v2.0.1)

CodePudding user response:

You can get a 10 x 10 matrix with 1 on the diagonal simply by doing diag(10). If you do diag(10)[,10:1] this reverses the column order, giving you 1s on the anti-diagonal. Therefore doing diag(10) diag(10)[,10:1] gives you a 10 x 10 matrix with 1s on both the diagonal and antidiagonal. Multiply this by 2 and you will have your expected result.

2 * (diag(10)   diag(10)[,10:1])
#>       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#>  [1,]    2    0    0    0    0    0    0    0    0     2
#>  [2,]    0    2    0    0    0    0    0    0    2     0
#>  [3,]    0    0    2    0    0    0    0    2    0     0
#>  [4,]    0    0    0    2    0    0    2    0    0     0
#>  [5,]    0    0    0    0    2    2    0    0    0     0
#>  [6,]    0    0    0    0    2    2    0    0    0     0
#>  [7,]    0    0    0    2    0    0    2    0    0     0
#>  [8,]    0    0    2    0    0    0    0    2    0     0
#>  [9,]    0    2    0    0    0    0    0    0    2     0
#> [10,]    2    0    0    0    0    0    0    0    0     2

Note that this method only works for square matrices with even numbers of rows / columns. If you have an odd number, the central cell will be double the expected value.

Created on 2022-05-28 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related