# Implementing the pivot algorithm for self-avoiding walks in 2 dimensions

``````rm(list=ls())

RW2D<-function(N)
{
i<-0
xdir<-0
ydir<-0
xpos<-vector()
xpos[1]<-xdir
ypos<-vector()
ypos[1]<-ydir
for (i in 1:N-1)
{
r<-runif(1)
if(r<=0.25) {xdir<-xdir+1}
if(r>0.25 && r<=0.5) {xdir<-xdir-1}
if(r>0.5 && r<=0.75) {ydir<-ydir +1}
if(r>0.75) {ydir<-ydir-1}
xpos[i+1]<-xdir
ypos[i+1]<-ydir
}
return(cbind(xpos,ypos))
}
rw<-RW2D(30)
rw
xmin<-min(rw[,1])
xmax<-max(rw[,1])
ymin<-min(rw[,2])
ymax<-max(rw[,2])

plot(rw[,1],rw[,2],type="l",xlab="x",ylab="y",main="Random Walk Simulation
In Two Dimensions",col="green4",xlim=range(xmin:xmax),ylim=range(ymin:ymax))

install.packages("purrr")
library(purrr)
rdunif(1,30,1) #choosing a pivot
rotation<-function(theta)
{
A= matrix(c(cos(theta),sin(theta),-sin(theta),cos(theta)),ncol=2,nrow=2,byrow=T)
return(A)
}

r90=rotation(pi/2);r90
r180=rotation(pi)
r270=rotation(3*pi/2)
list_matrix=list(r90,r180,r270)

newchain = rw[0:pivot,];newchain
tempchain= rw[(pivot+1) :n,]; tempchain

for( i in 1: n-pivot)
{

#matrix(unlist(sample(list_matrix, size=1)),ncol=2)%*%tempchain[i,]

}

``````

I'm trying to do the algorithm described here: https://arxiv.org/pdf/cond-mat/0109308.pdf

How do I store the resultant matrix?

See the FAQ: How to do a minimal reproducible example `reprex` for beginners. This is almost it, aside from

`pivot` is missing. A `reprex` gives you a chance to catch that before posting.

A couple of minor things:

is considered bad form, because someone running the `reprex` may have other objects in memory that they care, perhaps, deeply about.

also is bad form because it messes with the user's setup, which may be non-standard. Instead use

``````require(purrr)
``````

Without `pivot` I can't test, but what you probably need to do is to "catch" the return value of the for loop. That's as simple as

``````my_result  <- for(i in seq_along(source_object) my_code
``````

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.