1

正と負の整数の行列があります。特定の列 (以下の例では列 "a") で反対の符号を持つ任意の 2 つの行のすべての可能な組み合わせを合計して、この列にゼロが追加されるようにします。

結合された行の行が挿入されnewmatnewmat[,"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 に答える