I have created a polygon with 9 sides and a radius of 5 using the code below. I want to be able to take an object and move it around the polygon moving from side to side, while it is at the midpoint of the line, and have it keep running. I assume it is so type of loop but I am unsure how to do this. The object can be something like a dot that will move from the middle of each line to the one next to it.
theta = linspace( pi, -pi, 10);
r = 5;
x = r*cos(theta);
y = r*sin(theta);
plot(x,y,'r');
axis equal;
hold on;

답변 (1개)

Geoff Hayes
Geoff Hayes 2017년 2월 16일

0 개 추천

John - you may first want to determine those points along the polygon that you wish the object to traverse. You can use linspace to generate a linearly spaced array given a starting point and an end point. For example, for one side of the polygon you could do
polygonSideX = linspace(x(1), x(2), 100);
polygonSideY = linspace(y(1), y(2), 100);
You would repeat the above for each side and could combine the results into two arrays: one for the x-coordinates (of all sides) and one for the y-coordinates.
If you just want to move a simple dot around the polygon, then you can plot the initial position of that dot as
hDot = plot(polygonSideX(1), polygonSideY(2), 'g.');
Now you have a graphics object handle, hDot, to the dot that you have drawn given the first (x,y) coordinate. So what you want to do is then update the x and y data for this graphics object so that it's position changes
set(hDot,'XData',polygonSidesX(k), 'YData', polygonSidesY(k));
where k is the kth coordinate. You can put this in a loop, either a for loop that runs just once over all coordinates or a while loop so that the dot never stops moving (careful when you reach the last coordinate, you will need to then start at the beginning again).
And every time that you update the x and y data for the dot graphics object, call
pause(0.01)
which is a brief ten millisecond pause that will allow the new position of the dot to be drawn immediately.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2017년 2월 16일

답변:

2017년 2월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by