Hi Komal,
Try this:

walk2d<-function(n){
rw <- matrix(0, ncol = 2, nrow = n)

# generate the indices to set the deltas
indx <- cbind(seq(n), sample(c(1, 2), n, TRUE))

# now set the values
rw[indx] <- sample(c(-1, 1), n, TRUE)

# cumsum the columns
rw[,1] <- cumsum(rw[, 1])
rw[,2] <- cumsum(rw[, 2])
cbind(rw[,1],rw[,2])  # changed this

}

# example
n <- 100
rw <- walk2d(n)
plot(rw, xlab="x", ylab="y", main="Random Walk Simulation In Two
Dimensions",
     xlim = range(rw[,1]), ylim = range(rw[,2]), las = 1)

HTH,
Jorge


On Wed, Jun 29, 2011 at 11:44 AM, Komal <> wrote:

>
>
>
> walk.2d<-function(n)
> {
> rw <- matrix(0, ncol = 2, nrow = n)
>
> # generate the indices to set the deltas
> indx <- cbind(seq(n), sample(c(1, 2), n, TRUE))
>
> # now set the values
> rw[indx] <- sample(c(-1, 1), n, TRUE)
>
> # cumsum the columns
> rw[,1] <- cumsum(rw[, 1])
> rw[,2] <- cumsum(rw[, 2])
>
> return(rw[,1],rw[,2])
>
> }
> n<-1000
>
> plot(walk.2d(n), type="n",xlab="x",ylab="y",main="Random Walk Simulation In
> Two Dimensions",xlim=range(rw[,1]),ylim=range(rw[,2]))
>
>        # use 'segments' to color each path
> segments(head(rw[, 1], -1), head(rw[, 2], -1), tail(rw[, 1], -1), tail(rw[,
> 2], -1), col ="blue")
>
>
> This code is giving me error in the return()... what to write in
> return()???
> please help.
>
>
> --
> View this message in context:
> http://r.789695.n4.nabble.com/2d-rndom-walk-tp3632468p3633249.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help@r-project.org mailing list
> 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@r-project.org mailing list
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.

Reply via email to