Moving a square horizontally

18 views (last 30 days)
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

Accepted Answer

Geoff Hayes
Geoff Hayes on 18 Mar 2020
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 Comments
Nicolas Ortega
Nicolas Ortega on 9 Dec 2020
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 on 9 Dec 2020
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Graphics Object Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!