[R] loop over matrix: subscript out of bounds
Maija Sirkjärvi
m@|j@@@|rkj@rv| @end|ng |rom gm@||@com
Wed Aug 8 11:40:59 CEST 2018
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.)
>
> Rui Barradas
>
> 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]]
More information about the R-help
mailing list