1

我有一个正整数和负整数矩阵。我想将特定列中具有相反符号的任意两行的所有可能组合加在一起(下面我的示例中的列“a”),这样加法在该列中给出零。

合并的行行被放入newmat并且newmat[,"a"]只有零。

一个问题是,对于较大的矩阵(> 500 行),我的解决方案变得异常缓慢。

##initialize matrix
nof.rows <- 100
mat <- cbind(matrix(ncol=40, nrow=nof.rows, sample(40*nof.rows)),
         matrix(ncol=6, nrow=nof.rows, c(1,2,-1,3, -2, -3),
                dimnames=list(seq_len(nof.rows),c("a", "b", "c", "d", "e", "f"))))

newmat <- matrix(ncol=ncol(mat), nrow=0)

##column which will contain nothing but zeroes
col <- "a"

for (i in seq_len(nrow(mat))){
  curr.row <- mat[i,]
  curr.col <- mat[,col]
  opposite.sign.indices <- vector()
  if(curr.row[col] > 0)
    opposite.sign.indices <- which(curr.col<0)
  else
    opposite.sign.indices <- which(curr.col>0)
  opposite.sign.indices <- setdiff(opposite.sign.indices, seq_len(i))
  for (j in opposite.sign.indices){
      opposite.sign.row <- mat[j,]
      newrow <- (abs(opposite.sign.row[col]) * curr.row
                 + (abs(curr.row[col])*opposite.sign.row))
      newmat <- rbind(newmat, newrow)
    }
}

newmat <- unique(newmat)

关于如何加快进程的任何想法?提前谢谢-H-

4

1 回答 1

0

这要快得多:

##initialize matrix
nof.rows <- 100
mat <- cbind(matrix(ncol=40, nrow=nof.rows, sample(40*nof.rows)),
         matrix(ncol=6, nrow=nof.rows, c(1,2,-1,3, -2, -3),
                dimnames=list(seq_len(nof.rows),c("a", "b", "c", "d", "e", "f"))))
col="a"

pos.row.idx <- which(mat[,col]>0)
neg.row.idx <- which(mat[,col]<0)
newmat <- unique(t(apply(expand.grid(pos.row.idx, neg.row.idx), 1, function(x){
  abs(mat[x[2],col]) * mat[x[1],] + abs(mat[x[1],col]) * mat[x[2],]
})))
于 2013-03-28T15:42:17.853 回答