animating a line through two given points
조회 수: 4 (최근 30일)
이전 댓글 표시
Hi there I work with Simulink on dynamical areas. After running my current program, the coordinates of two lumped masses (let's say A and B) are transferred to Workspace which are four one-row matrices corresponding to x- and y-coordinates of all time steps of A and B. Actually I want to link these two points together as a line and animate it versus time. In fact I somehow dealt with it through the following commands
x=[xA(i) xB(i)];y=[yA(i) yB(i)]; hd=line(x,y);
but the problem is that it creates and shows all the produced lines from the start which eventually becomes a solid distributed surface rather than a moving line. I put it in different loops but I couldn't cope with it. So I would appreciate you if you would be able to help me. Regards Hossein
댓글 수: 0
답변 (1개)
nick
2025년 4월 14일
Hello hossein,
To animate a line connecting two points, you can update the existing line object rather than creating a new one at each time step, as shown in the code below :
xA = rand(1, 100); % Example x-coordinates for point A
yA = rand(1, 100); % Example y-coordinates for point A
xB = rand(1, 100); % Example x-coordinates for point B
yB = rand(1, 100); % Example y-coordinates for point B
figure;
hold on;
grid on;
% Set axis properties to prevent them from changing during animation
axis equal;
xlim([min([xA, xB]) - 0.1, max([xA, xB]) + 0.1]);
ylim([min([yA, yB]) - 0.1, max([yA, yB]) + 0.1]);
% Initialize the line object
hd = line([xA(1) xB(1)], [yA(1) yB(1)], 'Color', 'b', 'LineWidth', 2);
% Animation loop
for i = 1:length(xA)
% Update the line data
set(hd, 'XData', [xA(i) xB(i)], 'YData', [yA(i) yB(i)]);
% Pause for a short duration to control the speed of the animation
pause(0.05);
title(sprintf('Time step: %d', i));
end
hold off;
You can refer to the documentation by executing the following command in MATLAB Command Window to know more about 'set' function :
doc set
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Animation에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!