[英]Find a pattern of a matrix in R?
我有一個名為 my_matrix 的矩陣,它有 5 行 5 列,由 1 和 0 組成。
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
我想找到 test.matrix 的 left2tile 模式,如圖所示:
[,1] [,2]
[1,] 1 0
[2,] 1 0
我還想找到 test.matrix 的 right2tile 模式,如圖所示:
[,1] [,2]
[1,] 0 1
[2,] 0 1
對於left2tile,我想找到矩陣中最左邊的兩個條目為1,最右邊的兩個條目為0的唯一2-tile的數量。
對於 right2tile 我想找到矩陣中唯一 2 塊的數量,其中最右邊的兩個條目是 1,最左邊的兩個條目是 0。
我知道這些可能重疊。 知道如何在 R 中計算這個嗎?
以下是示例函數,可以告訴您較大矩陣中有多少 2x2 矩陣與提供的 2x2 矩陣匹配。 第一個助手 function 創建輸入矩陣組成的 2x2 矩陣列表。 第二個 function 使用第一個助手 function 並返回第一個矩陣參數中有多少在第二個矩陣參數中。
# 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.