基于初始邻接创建概率矩阵

时间:2017-12-24 17:02:21

标签: r

这显示了我的最终目标:

enter image description here

作为第一步,我已经使用下面的代码对其进行了尝试,但我对循环不够熟悉以创建正确的概率矩阵。关于如何更好地纳入邻接的任何想法?

spatialMatrix <- matrix(data = 1:20, ncol = 5, nrow = 4, byrow = T)
emptyMatrix <- matrix(data = 101, ncol = 4, nrow = 5)

lets <- which(spatialMatrix == 12, arr.ind = TRUE, useNames = F)
for (i in seq_along(1:as.numeric(ncol(emptyMatrix)-lets[,2]))) {
  for (j in seq_along(1:as.numeric(nrow(emptyMatrix)-lets[,1]))) {
    emptyMatrix[lets[,1], lets[,2]] <- 0
    emptyMatrix[lets[,1], lets[,2]+i] <- 0.4
    emptyMatrix[lets[,1], lets[,2]-i] <- 0.4
    # diagonals
    emptyMatrix[lets[,1]+j, lets[,2]+i] <- 0.4
    emptyMatrix[lets[,1]-j, lets[,2]+i] <- 0.4
    emptyMatrix[lets[,1]+j, lets[,2]-i] <- 0.4
    emptyMatrix[lets[,1]-j, lets[,2]-i] <- 0.4

    emptyMatrix[lets[,1]+j, lets[,2]] <- 0.4
    emptyMatrix[lets[,1]-j, lets[,2]] <- 0.4
  }

1 个答案:

答案 0 :(得分:0)

这是一个基本的r函数:我还将选择元素[3,2]从而从行中减去3,然后从列中减去2:

sm <- matrix(data = 1:20, ncol = 5, nrow = 4, byrow = T)
fun <- function(z)sapply(z,function(x)ifelse(x==0,0,switch(x,0.4,0.1,0.05)))
apply(pmax(abs(row(sm)-3),abs(col(sm)-2)),2,fun)
      [,1] [,2] [,3] [,4] [,5]
 [1,]  0.1  0.1  0.1  0.1 0.05
 [2,]  0.4  0.4  0.4  0.1 0.05
 [3,]  0.4  0.0  0.4  0.1 0.05
 [4,]  0.4  0.4  0.4  0.1 0.05

希望这会有所帮助 甚至更简洁的方式来编写上面的fun函数将是:

 fun <- function(z)sapply(as.character(z),switch,'0'=0,'1'=0.4,'2'=0.1,'3'=0.05)

此代码根据给定的空间矩阵创建行和列的矩阵,然后比较两者取最大值,然后根据获得的最大值分配概率