Moving a square horizontally

조회 수: 12 (최근 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 CenterFile Exchange에서 Graphics Object Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by