[R] loop over matrix: subscript out of bounds

S Ellison S@E|||@on @end|ng |rom LGCGroup@com
Wed Aug 8 13:59:42 CEST 2018


 
> >>>>> 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}}




More information about the R-help mailing list