对内核矩阵的R行操作

时间:2013-03-21 19:19:04

标签: r matrix linear-algebra

我有一个内核矩阵,如下所示:

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中的任何条目为否定。这段代码适用于我的几个例子,但它很容易给许多其他矩阵带来麻烦。

1 个答案:

答案 0 :(得分:1)

Yiour分配箭头指向错误的方向。

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