[R] loop over matrix: subscript out of bounds
Martin Maechler
m@ech|er @end|ng |rom @t@t@m@th@ethz@ch
Wed Aug 8 13:09:01 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
> }
>
> HTH,
> Eric
and why are you not using Enrico Schumann's even nicer solution
(from August 6) that I had mentioned too ?
Here's the link to it in the (official) R-help archives:
https://stat.ethz.ch/pipermail/r-help/2018-August/455673.html
Maija said
> Thanks, but I didn't quite get it. And I don't get it running as it should.
and actually she is right that that version does not work for
all dimensions of 'myMatrix' -- it does need ncol(.) >= 3
but neither does the above solution -- it only works for nrow(.) >= 2
Here's a function version of Enrico's that does work in all cases(!)
without a for loop -- including examples (as comments)
mkMat <- function(n=5, m=7) {
M <- matrix(0, n,m)
diag(M) <- -1
## this fails when m == ncol(M) <= 2, and ', drop=FALSE' does *not* help :
## diag(M[, -1]) <- 1
## diag(M[, -1, drop=FALSE]) <- 1
## This *does* work:
M[col(M) - row(M) == 1L] <- 1
M
}
mkMat()
## [,1] [,2] [,3] [,4] [,5] [,6] [,7]
## [1,] -1 1 0 0 0 0 0
## [2,] 0 -1 1 0 0 0 0
## [3,] 0 0 -1 1 0 0 0
## [4,] 0 0 0 -1 1 0 0
## [5,] 0 0 0 0 -1 1 0
mkMat(3,5)
## [,1] [,2] [,3] [,4] [,5]
## [1,] -1 1 0 0 0
## [2,] 0 -1 1 0 0
## [3,] 0 0 -1 1 0
mkMat(5,3)
## [,1] [,2] [,3]
## [1,] -1 1 0
## [2,] 0 -1 1
## [3,] 0 0 -1
## [4,] 0 0 0
## [5,] 0 0 0
## Show that all small (m,n) work:
for(m in 0:3)
for(n in 0:3) {
cat(sprintf("(%d,%d):\n", n,m)); print(mkMat(n,m))
}
## (output not shown here)
>
> On Wed, Aug 8, 2018 at 12:40 PM, Maija Sirkjärvi <maija.sirkjarvi using gmail.com>
> wrote:
>
> > [.............]
> > [.............]
> > However. The result that I would need to get would be like this:
> >
> > [,1] [,2] [,3] [,4] [,5] [,6] [,7]
> > [1,] -1 1 0 0 0 0 0
> > [2,] 0 -1 1 0 0 0 0
> > [3,] 0 0 -1 1 0 0 0
> > [4,] 0 0 0 -1 1 0 0
> > [5,] 0 0 0 0 -1 1 0
More information about the R-help
mailing list