参考一下这个
%制作动画
%挂摆横梁
plot([-0.2;0.2],[0;0],'color','y','linestyle','-',...
'linewidth',10);
%画初始位置的单摆
g=0.98; %重力加速度,可以调节摆的摆速
l=1;
theta0=pi/4;
x0=l*sin(theta0);
y0=(-1)*l*cos(theta0);
axis([-0.75,0.75,-1.25,0]);
axis('off'); %不显示坐标轴
%创建摆锤
head=line(x0,y0,'color','r','linestyle','.',...
'erasemode','xor','markersize',40);
%创建摆杆
body=line([0;x0],[0;y0],'color','b','linestyle','-',...
'erasemode','xor');
%摆的运动
t=0;
dt=0.01;
while 1
t=t+dt;
theta=theta0*cos(sqrt(g/l)*t);
x=l*sin(theta);
y=(-1)*l*cos(theta);
set(head,'xdata',x,'ydata',y);
set(body,'xdata',[0;x],'ydata',[0;y]);
drawnow;
end