简体   繁体   中英

Find a pattern of a matrix in R?

I have a matrix called my_matrix with 5 rows and 5 columns made up with 1s and 0s.

test.matrix <- matrix(c(0,0,1,0,0,0,1,1,1,0,0,1,1,1,0,0,0,0,1,0,0,1,0,0,1),nrow=5)
test.matrix

     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    0
[2,]    0    1    1    0    1
[3,]    1    1    1    0    0
[4,]    0    1    1    1    0
[5,]    0    0    0    0    1

I want to find a left2tile pattern of test.matrix as shown:

      [,1] [,2]
[1,]    1    0
[2,]    1    0

I also want to find a right2tile pattern of test.matrix as shown:

      [,1] [,2]
[1,]    0    1
[2,]    0    1

For left2tile I want to find the number of unique 2-tiles in the matrix where the leftmost two entries are 1 and the rightmost two entries are 0.

For right2tile I want to find the number of unique 2-tiles in the matrix where the rightmost two entries are 1 and the leftmost two entries are 0.

I'm aware that these may overlap. Any idea how to calculate this in R?

Here are example functions that can tell you how many 2x2 matrices in the bigger matrix match the provided 2x2 matrix. The first helper function creates a list of 2x2 matrices that the input matrix is made of. The second function uses the first helper function and returns how many of the first matrix argument is in the second matrix argument.

# Helper functions
decompose=function(x) {
  two_by_two=list()
  k=1
  for (i in 1:(nrow(x)-1)) {
    for (j in 1:(ncol(x)-1)) {
      two_by_two[[k]]=matrix(c(x[i,j], x[i+1,j], x[i,j+1], x[i+1,j+1]), ncol=2)
      k=k+1
    }
  }
  return(two_by_two)
}

how_many=function(x, test) {
  my_list=decompose(test)
  bools=sapply(my_list, function(y) {
    return(identical(x, y))
  })
  return(sum(bools))
}

#Carrying it out
left2tile=matrix(c(1,1,0,0), ncol=2)

right2tile=matrix(c(0,0,1,1),ncol=2)

how_many(left2tile, test.matrix)

how_many(right2tile, test.matrix)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM