MATLAB Answers

Moving a square horizontally

17 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

  0 Comments

Sign in to comment.

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

  0 Comments

Sign in to comment.

More Answers (0)