Hello,

There are now three solutions to the OP's problem.
I have timed them and the results depend on the matrix size.

The solution I thought would be better, Enrico's diag(), is in fact the slowest. As for the other two, Eric's for loop is 50% fastest than the matrix index for small matrices but its relative performance degrades as the matrix becomes bigger and bigger.


library(microbenchmark)

#Enrico Schumann
mkMat_diag <- function(nr = 5, nc = 7) {
    M <- matrix(0, nr, nc)
    diag(M) <- -1
    diag(M[, -1]) <- 1
    M
}

#Eric Berger
mkMat_loop <- function(nr = 5, nc = 7) {
    M <- matrix(0, nr, nc)
    for(i in 2:nrow(M)) {
       M[i - 1, i - 1] <- -1
       M[i - 1, i] <- 1
    }
    M
}


#S.Ellison
mkMat_index <- function(nr = 5, nc = 7) {
   M <- matrix(0, nr, nc)
   i <- 1:min(nr, nc)
   j <- i[i < nc]
   M[ cbind(i, i) ] <- -1
   M[ cbind(j, j + 1) ] <- 1
   M
}



microbenchmark(
    loop = mkMat_loop(),
    index = mkMat_index(),
    diag = mkMat_diag(),
    times = 1e3
)


microbenchmark(
    loop = mkMat_loop(50, 70),
    index = mkMat_index(50, 70),
    diag = mkMat_diag(50, 70)
)


microbenchmark(
    loop = mkMat_loop(500, 700),
    index = mkMat_index(500, 700),
    diag = mkMat_diag(500, 700)
)


Hope this helps,

Rui Barradas

On 08/08/2018 12:59, S Ellison wrote:

Eric Berger    on Wed, 8 Aug 2018 12:53:32 +0300 writes:

You only need one "for loop"
for(i in 2:nrow(myMatrix)) {
    myMatrix[i-1,i-1] = -1
    myMatrix[i-1,i] = 1
}

Or none, with matrix-based array indexing and explicit control of the indices 
to prevent overrun in :

mkMat <- function(n=5, m=7) {
    M <- matrix(0, n,m)
    i <- 1:min(n,m)
    j <- i[i<m]
    M[ cbind(i,i) ] <- -1
    M[ cbind(j, j+1) ] <- 1
    M
}




*******************************************************************
This email and any attachments are confidential. Any use...{{dropped:8}}

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to