简体   繁体   English

核矩阵上的R行运算

[英]R row operations on kernel matrix

I have a kernel matrix which looks as follows: 我有一个内核矩阵,如下所示:

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

Now I want to apply row operations such that kern[,c("c1b", "c2b", "c3b")] is the identity matrix. 现在,我想应用行操作,使kern[,c("c1b", "c2b", "c3b")]为单位矩阵。 I know that this is easily accomplished by substracting the second row from the third: 我知道,通过从第三行减去第二行可以轻松实现:

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

but is there a function in R which does that for me? 但是R中有一个函数对我有用吗? A function for the reduced row echelon form posted in another thread isn't what I need. 我不需要在另一个线程中发布的用于减少行梯形表格的功能。


EDIT 编辑

I have a clumsy solution 我有一个笨拙的解决方案

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")]

Also I forgot to mention that I do not want any entry in kern to be negative. 我也忘记提及我不希望kern任何条目都为负数。 This code works for my few examples, however, it is prone to cause trouble for many other matrices. 该代码适用于我的一些示例,但是,它很容易给其他许多矩阵带来麻烦。

Yiour assignment arrow is directed in the wrong direction. 您的分配箭头指向错误的方向。

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")]

You can attempt to replicate what your brain (or at least mine) did when asked to find the correct row to subtract from a row that had an off-axis non-zero entry: 您可以尝试复制您的大脑(或至少是我的大脑)在被要求找到正确的行以从具有离轴非零条目的行中减去时所做的事情:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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