Creating a 2D random walk

Asked by Ella Yeo

Ella Yeo (view profile)

on 28 May 2019
Latest activity Edited by James Tursa

James Tursa (view profile)

on 28 May 2019
I'm trying to create 2D random walk, (up,down,left and right)
I want to store every results into a empty vector x and y and mark the final position in a graph.
i've done this so far but it's not storing every single steps into a vector.
what did I do wrong?
steps_r=0; %number of steps to the right
steps_l=0; %numbers of steps to the left
steps_u=0;
steps_d=0;
n=5; %number of turns
x=[];
y=[];
start_x=0; %total number of steps in x-axis to finalise the coordinate
start_y=0;
for i =1:n
p_x=rand(1) %probability of x
p_y=rand(1) %probability of y
if p_x<0.6
start_x = start_x-1
x=[start_x]
steps_l=steps_l+1
elseif p_x>=0.6
start_x=start_x+1
x=[start_x]
steps_r=steps_r+1
elseif p_y<0.7
start_y= start_y+1
y=[start_y]
steps_u=steps_u+1
else
start_y=start_y-1
y=[start_y]
steps_d=steps_d+1
end
plot(x(1),y(1))
title('Position of a random walk')
xlabel('x')
ylabel('y')
end

Tags

Answer by Image Analyst

Image Analyst (view profile)

on 28 May 2019

Sorry I don't have time to analyze your code now, but in the meantime, you might want to take a look at my attached collection of random walk demos. They are well commented.

Answer by James Tursa

James Tursa (view profile)

on 28 May 2019
Edited by James Tursa

James Tursa (view profile)

on 28 May 2019

In this logic, you will never get to the y branches because one of the first two x branches will always be true:
if p_x<0.6
:
elseif p_x>=0.6
:
elseif p_y<0.7
:
else
:
end
You could separate them as follows:
if p_x<0.6
:
else
:
end
if p_y<0.7
:
else
:
end
But this will always give you a diagonal step. Maybe that is what you want, but I rather doubt it.
I suspect what you really want is to randomly change x or y but not both at the same time? In that case, simply assign probabilities to each possible step (+x, -x, +y, -y) such that they all add up to 1, and then use a variation of your current branching to do the stepping. I.e., at each iteration you pick one random number and then do one of the four possible steps based on that random value.