How can I create a plot with random directions?
조회 수: 5 (최근 30일)
이전 댓글 표시
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
채택된 답변
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])
추가 답변 (0개)
참고 항목
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!