[R] loop over matrix: subscript out of bounds
Enrico Schumann
e@ @ending from enrico@chum@nn@net
Mon Aug 6 13:23:48 CEST 2018
Quoting Maija Sirkjärvi <maija.sirkjarvi using gmail.com>:
> I have a basic for loop with a simple matrix. The code is doing what it is
> supposed to do, but I'm still wondering the error "subscript out of
> bounds". What would be a smoother way to code such a basic for loop?
>
> myMatrix <- matrix(0,5,12)
> for(i in 1:nrow(myMatrix)) {
> for(i in 1:ncol(myMatrix)) {
> myMatrix[i,i] = -1
> myMatrix[i,i+1] = 1
> }}
> print(myMatrix)
>
> Thanks in advance!
>
Perhaps you do not need loops at all?
myMatrix <- matrix(0, 5, 12)
diag(myMatrix) <- -1
diag(myMatrix[, -1]) <- 1
--
Enrico Schumann
Lucerne, Switzerland
http://enricoschumann.net
More information about the R-help
mailing list