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.