# [makes] hanging_chain_skeleton.mat# Solve the hanging chain QP (unconstrained problem, without ground constraints).# N mass points at positions (y_i, z_i) minimise total potential energy subject# to fixed endpoints.importnumpyasnpfromscipy.optimizeimportminimizefromscipy.ioimportsavematN=40m_i=40.0/ND_i=70.0*Ng0=9.81# Fixed endpoints.y_first,z_first=-2.0,1.0y_last,z_last=2.0,1.0# Optimise over the 2*(N-2) free interior coordinates interleaved as# [y_1, z_1, y_2, z_2, ..., y_{N-2}, z_{N-2}].defget_yz(x_free):y=np.empty(N)z=np.empty(N)y[0],z[0]=y_first,z_firsty[-1],z[-1]=y_last,z_lasty[1:-1]=x_free[0::2]z[1:-1]=x_free[1::2]returny,zdefobjective(x_free):y,z=get_yz(x_free)spring=D_i/2*np.sum((np.diff(y)**2+np.diff(z)**2))gravity=g0*m_i*np.sum(z)returnspring+gravityx0=np.zeros(2*(N-2))result=minimize(objective,x0,method='L-BFGS-B',options={'ftol':1e-12,'gtol':1e-10})Y0,Z0=get_yz(result.x)savemat('hanging_chain_skeleton.mat',{'Y0':Y0,'Z0':Z0})