Moving a square horizontally

18 ビュー (過去 30 日間)
Alexander Tollinger
Alexander Tollinger 2020 年 3 月 18 日
コメント済み: Geoff Hayes 2020 年 12 月 9 日
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]).
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]);
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

採用された回答

Geoff Hayes
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
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
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 ExchangeGraphics Object Programming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by