# [R] loop over matrix: subscript out of bounds

Eric Berger er|cjberger @end|ng |rom gm@||@com
Wed Aug 8 11:53:32 CEST 2018

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

On Wed, Aug 8, 2018 at 12:40 PM, Maija Sirkjärvi <maija.sirkjarvi using gmail.com>
wrote:

> Thanks!
>
> If I do it like this:
>
> myMatrix <- matrix(0,5,5*2-3)
> print(myMatrix)
> for(i in 2:nrow(myMatrix))
>   for(j in 2:ncol(myMatrix))
>     myMatrix[i-1,j-1] = -1
>     myMatrix[i-1,j] = 1
> print(myMatrix)
>
> I get the following result:
>
>    [,1] [,2] [,3] [,4] [,5] [,6] [,7]
> [1,]   -1   -1   -1   -1   -1   -1    0
> [2,]   -1   -1   -1   -1   -1   -1    0
> [3,]   -1   -1   -1   -1   -1   -1    0
> [4,]   -1   -1   -1   -1   -1   -1    1
> [5,]    0    0    0    0    0    0    0
>
> 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
>
> I'd rather not create symmetric matrices as I would really like to learn
> how to do this thing "the hard way" as I find matrix iteration to be quite
> a basic procedure in everything I'm trying to do.
>
> Thanks again!
> Maija
>
>
>
>
> ti 7. elok. 2018 klo 17.37 Rui Barradas (ruipbarradas using sapo.pt) kirjoitti:
>
> > Hello,
> >
> > If it is not running as you want it, you should say what went wrong.
> > Post the code that you have tried and the expected output, please.
> > (In fact, the lack of expected output was the reason why my suggestion
> > was completely off target.)
> >
> >
> > On 07/08/2018 09:20, Maija Sirkjärvi wrote:
> > > Thanks, but I didn't quite get it. And I don't get it running as it
> > should.
> > >
> > > ti 7. elok. 2018 klo 10.47 Martin Maechler (maechler using stat.math.ethz.ch
> > > <mailto:maechler using stat.math.ethz.ch>) kirjoitti:
> > >
> > >
> > >      > Thanks for help!
> > >      > However, changing the index from i to j for the column vector
> > >     changes the
> > >      > output. I would like the matrix to be the following:
> > >
> > >      > -1 1 0 0 0 0 0
> > >      > 0 -1 1 0 0 0 0
> > >      > 0 0 -1 1 0 0 0
> > >      > .....
> > >      > etc.
> > >
> > >      > How to code it?
> > >
> > >     as Enrico Schumann showed you:  Without any loop, a very nice
> > >     R-ish way (see his message)!
> > >
> > >     Martin
> > >
> > >      > Best,
> > >      > Maija
> > >
> >
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help