0

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?

Arron
  • 25
  • 7
  • 1
    Possible duplicate of [Trying to find the number of diagonals of 1 in each 3x3 tile in a 15x15 binary matrix?](https://stackoverflow.com/questions/58580834/trying-to-find-the-number-of-diagonals-of-1-in-each-3x3-tile-in-a-15x15-binary-m) – jay.sf Oct 31 '19 at 13:46
  • @G.Grothendieck I am looking for main diagonals and reverse main diagonals. I have included an example in my question. – Arron Oct 31 '19 at 19:26
  • @G.Grothendieck I have provided expected output for the example provided. – Arron Nov 02 '19 at 08:58

1 Answers1

0

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))
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • Can this be used with the list though @G.Grothendieck? I have tried this and I get `Error in zoo(data) : “x” : attempt to define invalid zoo object`. I also have more than 3 matrices in my list I just included 3 examples for this question. – Arron Nov 02 '19 at 09:03
  • Have added that. – G. Grothendieck Nov 02 '19 at 11:55