%挂摆横梁
plot([-0.2;0.2],[0;0],'color','y','linestyle','-',...
'linewidth',10);
%画初始位置的单摆
g=0.098; %重力加速度,可以调节摆的摆速
l1=1;
l2=0.8;
l3=0.6;
theta0=pi/4;
x01=l1*sin(theta0);
y01=(-1)*l1*cos(theta0);
x02=l2*sin(theta0);
y02=(-1)*l2*cos(theta0);
x03=l3*sin(theta0);
y03=(-1)*l3*cos(theta0);
axis([-0.75,0.75,-1.25,0]);
axis('off'); %不显示坐标轴
%创建摆锤
head1=line(x01,y01,'color','r','linestyle','.',...
'erasemode','xor','markersize',40);
head2=line(x02,y02,'color','g','linestyle','.',...
'erasemode','xor','markersize',40);
head3=line(x03,y03,'color','b','linestyle','.',...
'erasemode','xor','markersize',40);
%创建摆杆
body1=line([0;x01],[0;y01],'color','b','linestyle','-',...
'erasemode','xor');
body2=line([0;x02],[0;y02],'color','b','linestyle','-',...
'erasemode','xor');
body3=line([0;x03],[0;y03],'color','b','linestyle','-',...
'erasemode','xor');
%摆的运动
t=0;
dt=0.1;
while t< 30
t=t+dt;
theta1=theta0*cos(sqrt(g/l1)*t);
x1=l1*sin(theta1);
y1=(-1)*l1*cos(theta1);
set(head1,'xdata',x1,'ydata',y1);
set(body1,'xdata',[0;x1],'ydata',[0;y1]);
theta2=theta0*cos(sqrt(g/l2)*t);
x2=l2*sin(theta2);
y2=(-1)*l2*cos(theta2);
set(head2,'xdata',x2,'ydata',y2);
set(body2,'xdata',[0;x2],'ydata',[0;y2]);
theta3=theta0*cos(sqrt(g/l3)*t);
x3=l3*sin(theta3);
y3=(-1)*l3*cos(theta3);
set(head3,'xdata',x3,'ydata',y3);
set(body3,'xdata',[0;x3],'ydata',[0;y3]);
drawnow;
end
![](/picurl?url=https%3A%2F%2Fiknow-pic.cdn.bcebos.com%2Fd1160924ab18972b0e233750e2cd7b899e510a0a%3Fx-bce-process%3Dimage%252Fresize%252Cm_lfit%252Cw_600%252Ch_800%252Climit_1%252Fquality%252Cq_85%252Fformat%252Cf_auto)