如何让 MATLAB 代码为弹跳球制作动画
How do I make the MATLAB code animate a bouncing ball
close all;
clear all;
clc;
% height and period of time per data change
timeStep = 0.0005;
height = zeros(4e4,1);
% acceleration
g = 9.81;
% COR and initial height
COR = 0.8;
height(1)=15;
% initial speed
v = 0;
for i=2:length(height)
v = v - g*timeStep;
%new height
height(i)=max(0,height(i-1)+v*timeStep);
% stop ball from going below ground
if height(i)<=0
% change velocity direction
v = -COR*v;
end
end
% plot height on y and time on x axis
time = (1:4e4)*timeStep;
plot(time,height);
% turn into animation
%z = plot(time,height,'o','markerfacecolor','r','markersize',11);
i = 0;
while 1
%set(z,'XData',time,'YData',height);
%drawnow
time2 = time(i);
height2 = height(i);
plot(time2,height2,'o','markerfacecolor','r','markersize',11);
axis([0 15 0 15]);
i = i + 1;
pause(0.1);
end
grid on;
box on;
我发现了一个小错误。您的索引 i
应该从 1 而不是 0 开始。
除此之外,您所需要的只是用 drawnow
更新图表。可以找到文档 here.
由于您在评论中提供了此方法,我建议您看一下
pause(0.1)
因为这意味着您的动画需要超过 16 分钟才能完成。由于时间步长较小,您的图表可能在您没有注意到的情况下进行了更新。
使用您注释掉的代码是一种可能的解决方案。
% turn into animation
z= plot(time(1),height(1),'o','markerfacecolor','r','markersize',11);
axis([0 15 0 15]);
grid on;
box on;
for i = 2:length(height)
set(z,'XData',time(i),'YData',height(i));
drawnow limitrate
end
close all;
clear all;
clc;
% height and period of time per data change
timeStep = 0.0005;
height = zeros(4e4,1);
% acceleration
g = 9.81;
% COR and initial height
COR = 0.8;
height(1)=15;
% initial speed
v = 0;
for i=2:length(height)
v = v - g*timeStep;
%new height
height(i)=max(0,height(i-1)+v*timeStep);
% stop ball from going below ground
if height(i)<=0
% change velocity direction
v = -COR*v;
end
end
% plot height on y and time on x axis
time = (1:4e4)*timeStep;
plot(time,height);
% turn into animation
%z = plot(time,height,'o','markerfacecolor','r','markersize',11);
i = 0;
while 1
%set(z,'XData',time,'YData',height);
%drawnow
time2 = time(i);
height2 = height(i);
plot(time2,height2,'o','markerfacecolor','r','markersize',11);
axis([0 15 0 15]);
i = i + 1;
pause(0.1);
end
grid on;
box on;
我发现了一个小错误。您的索引 i
应该从 1 而不是 0 开始。
除此之外,您所需要的只是用 drawnow
更新图表。可以找到文档 here.
由于您在评论中提供了此方法,我建议您看一下
pause(0.1)
因为这意味着您的动画需要超过 16 分钟才能完成。由于时间步长较小,您的图表可能在您没有注意到的情况下进行了更新。
使用您注释掉的代码是一种可能的解决方案。
% turn into animation
z= plot(time(1),height(1),'o','markerfacecolor','r','markersize',11);
axis([0 15 0 15]);
grid on;
box on;
for i = 2:length(height)
set(z,'XData',time(i),'YData',height(i));
drawnow limitrate
end