How to fill in secondary diagonal

Yeah so the question is simple. Is there a way of filling anti-diagonal (or secondary diagonal) with a number.
I know that you can do
diag(A) = 2
for A, but what about anti-diagonal
Any help would be much appreciated. :slight_smile:

This should work:

mm <- matrix(rep(0, 9), nrow = 3)
mm
#>      [,1] [,2] [,3]
#> [1,]    0    0    0
#> [2,]    0    0    0
#> [3,]    0    0    0

mm[upper.tri(mm)] <- 1
mm[lower.tri(mm)] <- 2
mm
#>      [,1] [,2] [,3]
#> [1,]    0    1    1
#> [2,]    2    0    1
#> [3,]    2    2    0

Created on 2020-10-08 by the reprex package (v0.3.0)

Iยดm sorry, If I was unclear with what I needed. I would actually need it to be like this, if I have n number of collums and rows
#> [,1] [,2] [,3]
#> [1,] 0 0 2
#> [2,] 0 2 0
#> [3,] 2 0 0

Oops, sorry, I misunderstood.

library(rray)

mm <- matrix(rep(0, 9), nrow = 3)
mm
#>      [,1] [,2] [,3]
#> [1,]    0    0    0
#> [2,]    0    0    0
#> [3,]    0    0    0

diag(mm) <- 2
mm <- rray_flip(mm, 1)
mm
#>      [,1] [,2] [,3]
#> [1,]    0    0    2
#> [2,]    0    2    0
#> [3,]    2    0    0

There has to be an easier way to do this, but this works.

Wow this would solve my problem, but when I enter the library(rray) command it tells me, that there is no package called rray :frowning:

Yes, to use this solution you would need to install rray first:

install.packages("rray")

or

remotes::install_github("r-lib/rray")

Thanks a lot. Works like a charm. :slight_smile:

1 Like

You can reference the indices of the anti-diagonal to fill in those values. For example:

mm <- matrix(rep(0, 9), nrow = 3)
mm[cbind(nrow(mm):1, 1:nrow(mm))] = 2
mm
     [,1] [,2] [,3]
[1,]    0    0    2
[2,]    0    2    0
[3,]    2    0    0

Turn it into a function:

adiag = function(x, val) {
  n = nrow(x)
  x[cbind(n:1, 1:n)] = val
  x
}

mm <- matrix(rep(0, 9), nrow = 3)
adiag(mm, 2)
     [,1] [,2] [,3]
[1,]    0    0    2
[2,]    0    2    0
[3,]    2    0    0

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.