[R] loop over matrix: subscript out of bounds

Maija Sirkjärvi m@|j@@@|rkj@rv| @end|ng |rom gm@||@com
Tue Aug 7 09:36:10 CEST 2018


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?

Best,
Maija


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



ma 6. elok. 2018 klo 13.58 Rui Barradas (ruipbarradas using sapo.pt) kirjoitti:

> Hello,
>
> Eric is right but...
>
> You have two assignments. The second sets a value that will be
> overwritten is the next iteration by myMatrix[i,i] = -1 when 'i' becomes
> the next value.
>
> If you fix the second index and use 'j', you might as well do
>
> myMatrix[] = -1
> myMatrix[, ncol(myMatrix)] = 1
>
> Hope this helps,
>
> Rui Barradas
>
> Às 10:24 de 06/08/2018, Eric Berger escreveu:
> > Both loops are on 'i', which is a bad idea. :-)
> > Also myMatrix[i,i+1] will be out-of-bounds if i = ncol(myMatrix)
> >
> >
> > On Mon, Aug 6, 2018 at 12:02 PM, Maija Sirkjärvi <
> maija.sirkjarvi using gmail.com>
> > wrote:
> >
> >> 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!
> >>
> >>          [[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
> >> PLEASE do read the posting guide http://www.R-project.org/
> >> posting-guide.html
> >> and provide commented, minimal, self-contained, reproducible code.
> >>
> >
> >       [[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
> > PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
> >
>

	[[alternative HTML version deleted]]




More information about the R-help mailing list