Matlab random walk problem

4 views (last 30 days)
Abdulla Almatrafi
Abdulla Almatrafi on 28 Jan 2019
Consider the random walk example done in class. (Pick three non-collinear points (make a triangle). Then start at one of the points. Then we pick a number 1, 2, or 3 randomly and go halfway to that point. Repeat the process as many times as desired.)
What happens if we use a square instead of a triangle for our walk? What about a pentagon? Generate images for both a square and pentagon. Use at least 50,000 points. In class, each corner had equal chance of being chosen (1/3). Rewrite the random walk code to allow for the chance a corner is chosen to be specified. Generate the image for a square in which the bottom-left corner has a 10% chance of being chosen, the top-left has a 30% chance of being chosen, the top-right has a 25% chance of being chosen, and the bottom-right has a 35% chance of being chosen. Use at least 50,000 points.
clear
clc
x_corner=[0, 0, 1];
y_corner=[0, 1, 1];
num_steps=50000;
x=zeros(1,num_steps);
y=zeros(1,num_steps);
for i=2:num_steps
corner_num=randi(3);
x(i)=(x(i-1)+x_corner(corner_num))/2;
y(i)=(y(i-1)+y_corner(corner_num))/2;
% if corner_num == 1
% x(i)=x(i-1)./2;
% y(i)=y(i-1)./2;
% elseif corner_num == 2
% x(i)=(x(i-1)+0.5)./2;
% y(i)=(y(i-1)+0.5)./2;
% else
% x(i)=(x(i-1)+1)./2;
% y(i)=y(i-1)./2;
% end
end
plot(x,y,'k.')
i need some help in explaining
x(i)=(x(i-1)+x_corner(corner_num))/2;
y(i)=(y(i-1)+y_corner(corner_num))/2;
% if corner_num == 1
% x(i)=x(i-1)./2;
% y(i)=y(i-1)./2;
% elseif corner_num == 2
% x(i)=(x(i-1)+0.5)./2;
% y(i)=(y(i-1)+0.5)./2;
% else
% x(i)=(x(i-1)+1)./2;
% y(i)=y(i-1)./2;
% end
end
plot(x,y,'k.')
ive been trying to wrap my head around this code but why is there a +0.5 on the first elseif and a +1 on he second one i dont get it.
also is this necessary
x(i)=(x(i-1)+x_corner(corner_num))/2;
y(i)=(y(i-1)+y_corner(corner_num))/2;
or should i just use the if statment and erase that.
Thank you!

Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!