0
votes

I am trying to find the count of diagonal 1s in each 3x3 tile e.g.

0 0 1         1 0 0           1 1 1         0 1 1
0 1 0         0 1 0           1 1 1         0 1 0
1 0 0    or   0 0 1     or    1 1 1    or   1 0 0 

just for example where it doesn't matter about the other values in the 3x3 tile just the diagonals. By diagonals I mean the main diagonals as well as the reverse main diagonals. For example the following matrix would output 3 diagonals,

1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
1 1 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 

I am reading in a list of matrices...

set.seed(1234)
mat1 <- matrix(sample(c(0,1), 225, prob=c(0.8,0.2), replace=TRUE), nrow = 15)

set.seed(99)
mat2 <- matrix(sample(c(0,1), 225, prob=c(0.8,0.2), replace=TRUE), nrow = 15)

set.seed(123)
mat3 <- matrix(sample(c(0,1), 225, prob=c(0.8,0.2), replace=TRUE), nrow = 15)


mat_list <- list(mat1, mat2, mat3)

Any suggestions as to how this could be done?

1
@G.Grothendieck I am looking for main diagonals and reverse main diagonals. I have included an example in my question.Arron
@G.Grothendieck I have provided expected output for the example provided.Arron

1 Answers

0
votes

Assuming m is as shown in the Note at the end (and in particular the entries are double and not integer), the positions are at fixed distances so we can use rollapply with the function identical.

library(zoo)

num_diags <- function(m) {
  nr <- nrow(m)
  sum(rollapply(c(m), list(c(0, nr+1, 2*nr+2)), identical, c(1, 1, 1))) +
    sum(rollapply(c(m), list(c(0, nr-1, 2*nr-2)), identical, c(1, 1, 1)))
}

num_diags(m)
## 3

To apply this to a list of matrices:

sapply(mat_list, num_diags)

Note

m <- structure(c(1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 
0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 
0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(8L, 
15L), .Dimnames = list(NULL, NULL))