How can I create a plot with random directions?

조회 수: 10 (최근 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 CenterFile Exchange에서 Programming에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by