# Re: [R] matrix loop

From: David Winsemius <dwinsemius_at_comcast.net>
Date: Sat, 9 Feb 2008 20:00:52 +0000 (UTC)

John Kane <jrkrideau_at_yahoo.ca> wrote in
news:375101.56779.qm_at_web32803.mail.mud.yahoo.com:

> You are trying to create a matrix in the loop
>
> Try creating the matrix before the loop
> m <- 1:5
> n<-1:10
> y <- matrix(rep(NA, 50), nrow=m)

# I think that this might actually work:

y <- matrix(rep(NA, 50), nrow=max(m))

> for(i in 1:length(m))
> { for(j in 1:length(n))
> {
> y[i,j]=sum(i,j)
> }
> }

#produced:
Error in y[i, j] = sum(i, j) : subscript out of bounds

```--
David Winsemius

>
> However as Jim Holtman points out you can do this

> particular matrix by
>
>   outer(1:5, 1:10, "+")
>
>
> --- mohamed nur anisah <nuranisah_mohamed_at_yahoo.com>
> wrote:
>
>> Dear list,
>>
>>   I'm trying to make a loop of a (5x10) matrix and
>> below are my codes. Could anybody help me figure out
>> why my loop is not working. Thanks in advance!!
>>
>>
>>   m<-1:5
>> n<-1:10
>> for(i in 1:length(m))
>> { for(j in 1:length(n))
>>  {
>>   y[i,j]=sum(i,j)
>>   y<-as.matrix(y[i,j])
>>  }
>>   }
>>   cheers,

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help