Moving a square horizontally
7 次查看(过去 30 天)
显示 更早的评论
Hi guys,
I need to move the square along horizontally, where the time in which the square moves, is calculated via the expression below. (you can use random numbers for x_0, tau, and w[omega]).
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/277867/image.png)
The code looks like this:
%% create a square
x1=10, y1=10;
x2=10, y2=20;
x3=20, y3=20;
x4=20, y4=10;
x5=10, y5=10;
x_M = y2-5, y_M = 15; %set middle point
%% create the figure
figure(1);
x = [x1, x2, x3, x4, x5];
y = [y1, y2, y3, y4, y5];
plot(x, y, 'b-', 'LineWidth', 2 );
hold on;
plot(x_M,y_M, 'o');
xlim([0 40]);
ylim([0 40]);
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/277870/image.png)
Now I need to make the square move somehow using the pause() function of matlab.
Hope someone can help me figure this out.
Cheers,
Alex
0 个评论
采纳的回答
Geoff Hayes
2020-3-18
Alexander - if you save the handles to the graphics objects that correspond to the square and the centre of the square, then you can update their XData on each iteration of a loop and so move both objects. In the below example, I will just be adding 1 to the current x position of both objects (you would replace this with your equation):
%% create the figure
figure(1);
x = [x1, x2, x3, x4, x5];
y = [y1, y2, y3, y4, y5];
hSquare = plot(x, y, 'b-', 'LineWidth', 2 ); % save the handle to the square grapics object
hold on;
hSquareCentre = plot(x_M,y_M, 'o'); % save the handle to the square centre
xlim([0 40]);
ylim([0 40]);
% move the objects one unit to the right for 10 seconds
for k = 1:10
set(hSquareCentre, 'XData',get(hSquareCentre, 'XData') + 1);
set(hSquare, 'XData', get(hSquare, 'XData') + 1);
pause(1);
end
2 个评论
Nicolas Ortega
2020-12-9
If you are doing this using "n=4 for k=1:n" how do I make the box dissapear after it stops, between each cycle?
Geoff Hayes
2020-12-9
Nicholas - I'm not sure I understand your question, but the
set(hSquareCentre, 'XData',get(hSquareCentre, 'XData') + 1);
set(hSquare, 'XData', get(hSquare, 'XData') + 1);
changes the XData for both squares so that there is no need to make the previous box "disappear" as there is only one box (or two in this case for the centre) that is moving on each iteration.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graphics Object Programming 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!