How can I create a plot with random directions?
4 views (last 30 days)
Show older comments
Hello,
I am trying to plot someone walking randomly foward, right, left or backwards.
I tried creating a random generator between 1 to 4, where numbers in the interval [1, 4] are assigned to either foward, right, left, of backwards.
E.g. if it generates 1, the plot will go 1 step upwards in positive y-direction.
Here is what I have coded, which does not work so far.
foward = 1;
left = 2;
right = 3;
backward = 4;
for n = 0:50
randomgenerator = randi([1 4]);
if randomgenerator == 1
y = 1; %go foward
elseif randomgenerator == 2
y = -1; %go left
elseif randomgenerator == 3
y = 1; %go right
elseif randomgenerator == 4
y = -1; %go backwards
end
end
plot(y);
When I plot it nothing comes up. I also have a problem where I am not sure what value to add to "y" to go foward or backwards, since they are same as right and left.
0 Comments
Accepted Answer
Dave B
on 22 Oct 2021
Edited: Dave B
on 22 Oct 2021
It looks to me like left and backwards are kindof the same thing...how about adding x to differentiate them?
foward = 1;
left = 2;
right = 3;
backward = 4;
for n = 0:50
randomgenerator = randi([1 4]);
if randomgenerator == 1
x = 0;
y = 1; %go foward
elseif randomgenerator == 2
x = -1;
y = 0; %go left
elseif randomgenerator == 3
x = 1;
y = 0; %go right
elseif randomgenerator == 4
x = 0;
y = -1; %go backwards
end
end
plot([0 x],[0 y])
axis([-1 1 -1 1])
Even better, you could use a quiver so you could see the direction:
figure
quiver(0,0,x,y)
axis([-1 1 -1 1])
Or, to be really cool, maybe rethink the whole problem as polar!
figure
direction = randi([0 3])/2*pi;
polarplot([0 direction],[0 1])
More Answers (0)
See Also
Categories
Find more on 2-D and 3-D Plots in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!