0

I would like to convert some MATLAB code in R to represent a Two-dimensional and Three-dimensional random walk.

I have this interesting MATLAB code from a professor's notes which I cannot run properly in MATLAB:

%%TWO-DIMENSIONAL RANDOM WALK%% ALERT: NOT WORKING!
n=100000;
colorstr=['b' 'r' 'g' 'y'];
for k=1:4
z=2.*(rand(2,n)¡0.5)-1; %MATLAB does not understand "¡"
x=[zeros(1,2); cumsum(z')];
col=colorstr(k);
plot(x(:,1),x(:,2),col);
hold on
end grid

and

%%THREE-DIMENSIONAL RANDOM WALK%% WORKING FINE
p=0.5;
n=100;
colorstr=['b' 'r' 'g' 'y'];
for k=1:4
z=2.*(rand(3,n)<=p)-1;
x=[zeros(1,3); cumsum(z')];
col=colorstr(k);
plot3(x(:,1),x(:,2),x(:,3),col);
hold on
end

For the two dimensional r. walk I found a -very large code in https://stat.ethz.ch/pipermail/r-help/2010-December/261947.html However I would like to translate the above code to R in a very simplistic way. What I have done by the moment is

%%TWO-DIMENSIONAL RANDOM WALK%%    
n<-100000
%%%colorstr=c('b','r','g','y') %hesitating
colorstr=c('brgy')
for(i in 1:4){
z=2*(c(runif(n),runif(n))*0.5)-1
print(z)}
x=(array(0,1);cumsum(z^-1))

However, I think it is necessary to create a function just to output results. Can anyone help me with this task? All comments and useful help will be rewarded. Thank you in advance.

fina
  • 429
  • 4
  • 12

1 Answers1

1

here is a possible solution for the 2d random walk (3d can be done in the same way). I am not fluent in Matlab so some parts of the code I did not understand.

n <- 100
p <- 1/2
set.seed(1) #set a random seed to make example reproducible.
noise2 <- matrix(sample(c(-1, 1), n*2, replace = T, prob = c(1-p, p)), ncol = 2)
noise2 <- rbind(c(0, 0), noise2)
rw2 <- apply(noise2, 2, cumsum)

plot(rw2, type = "l", col = "dodgerblue", xlab = "", ylab = "", lwd = 2)

I simulate the noise not using runif but sample. This gives me a vector of length 2n containing only -1 and +1. I convert this vector into a matrix with two columns. After that I add a row at the top of this matrix which contains zeros.

Finally, using apply and cumsum I create the random walk. What apply does is it applies the function cumsum to every column of noise2.

Hope this helps a little. enter image description here

Cettt
  • 11,460
  • 7
  • 35
  • 58