david h shanabrook
2010-Aug-14 23:49 UTC
[R] incrementing matrix elements more efficiently
I need to increment cells of a matrix (collusionM). The indexes to increment are in an index (matchIndex). This is some of the code for (j in 1:(rows-1)) matchIndex[[j]] <- which(mx[j]==mx) for (j in 1:(rows-1)) collisionM[j,matchIndex[[j]]] <- collisionM[j,matchIndex[[j]]] + 1 I could put them in the same loop but this is slower. The first for statement is fine. It finds the matches and creates a list of the matches. The second is too slow, it increments the sparse matrix elements. Let me know if I need to put in more complete code to make this understandable. [[alternative HTML version deleted]]
david h shanabrook
2010-Aug-15 00:43 UTC
[R] incrementing matrix elements more efficiently
I need to increment cells of a matrix (collusionM). The indexes to increment are in an index (matchIndex). This is sample code library(seqinr) library(Matrix) x <- "abcabcabc" mx <- s2c(x) collisionM <- Matrix(0,nrow=10, ncol=10, sparse=TRUE) matchIndex <- list() rows <- length(mx) for (j in 1:(rows)) matchIndex[[j]] <- which(mx[j]==mx) for (j in 1:(rows)) collisionM[j,matchIndex[[j]]] <- collisionM[j,matchIndex[[j]]] + 1 Works fine, except with my data (rows=32000) it is too slow. The problem is the second for loop, where it increments the index of the sparse matrix; this needs to be rewritten so it is more efficient. Any ideas?