How can I create a plot with random directions?

11 vues (au cours des 30 derniers jours)
abbyeit
abbyeit le 22 Oct 2021
Commenté : abbyeit le 25 Oct 2021
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.

Réponse acceptée

Dave B
Dave B le 22 Oct 2021
Modifié(e) : Dave B le 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])
  1 commentaire
abbyeit
abbyeit le 25 Oct 2021
WOAH! Thank you so much, this is so cool.
I have no idea how I did not think of adding x, that seems completely obvious!
The polar thing looks really cool, I will try it.
Thank you!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by