对核矩阵进行R行运算



我有一个核矩阵,看起来如下:

kern <- matrix(c(1,0,0,1,0,0,0,1,1,0,1,1,0,0,1,0,0,1), dimnames=list(c("r1", "r1", "r3"), c("c1a", "c1b", "c2a", "c2b", "c3a", "c3b")), ncol=6, nrow=3)
> kern
   c1a c1b c2a c2b c3a c3b
r1   1   1   0   0   0   0
r2   0   0   1   1   0   0
r3   0   0   1   1   1   1

现在我想应用行运算使得kern[,c("c1b", "c2b", "c3b")]是单位矩阵。我知道这很容易通过第三行减去第二行来完成:

kern[3,] = kern[3,] - kern[2,]

但是R中是否有一个函数可以帮我做到这一点?一个函数的行简化阶梯形张贴在另一个线程不是我需要的。


编辑

我有一个笨拙的解决办法

sub <- kern[,c("c1b", "c2b", "c3b")]
for (i in which(colnames(kern) %in% colnames(sub))){
  ##identify which columns have more than one entry
  nonzero.row.idx <- which(kern[,i] != 0)
  while(length(nonzero.row.idx) > 1){    
    row.combinations <- combn(nonzero.row.idx, 2)
    for (j in ncol(row.combinations)){
      r1.idx <- row.combinations[1,j]
      r2.idx <- row.combinations[2,j]
      r1 <- kern[r1.idx,]
      r2 <- kern[r2.idx,]
      if (min(r1 - r2) >=0)
        kern[r1.idx, ] <- r1-r2
      else if (min(r2 - r1) >=0)
        kern[r2.idx, ] <- r2-r1
      else
        stop("Producing negative entries in row")      
      nonzero.row.idx <- which(kern[,i] != 0)
    }
  }
}      
kern[,c("c1b", "c2b", "c3b")]

我还忘了提到,我不希望kern中的任何条目为负。这段代码适用于我的几个示例,但是,对于许多其他矩阵,它很容易造成麻烦。

您的赋值箭头指向错误的方向。

kern <-  matrix(c(1,0,0,1,0,0,0,1,1,0,1,1,0,0,1,0,0,1), 
           dimnames=list(c("r1", "r1", "r3"), 
                         c("c1a", "c1b", "c2a", "c2b", "c3a", "c3b")),
           ncol=6, nrow=3)
sub <- kern[,c("c1b", "c2b", "c3b")]

你可以尝试复制你的大脑(或至少是我的)在被要求找到正确的行来减去具有离轴非零条目的行时所做的事情:

id <- which( sub != 0 & row(sub) != col(sub), arr.ind=TRUE)
id
#   row col
#r3   3   2
> sub[ id[ ,"row" ], ] <- sub[id[ ,"row" ] , ] - sub[id[, "col" ], ]
> sub
   c1b c2b c3b
r1   1   0   0
r1   0   1   0
r3   0   0   1

相关内容

  • 没有找到相关文章

最新更新