How can I create a plot with random directions?

3 ビュー (過去 30 日間)
abbyeit
abbyeit 2021 年 10 月 22 日
コメント済み: abbyeit 2021 年 10 月 25 日
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.

採用された回答

Dave B
Dave B 2021 年 10 月 22 日
編集済み: Dave B 2021 年 10 月 22 日
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 件のコメント
abbyeit
abbyeit 2021 年 10 月 25 日
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!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by