Turn linear formula into matrix form and ensure they are coordinated in the right position?

47 Views Asked by At

I want to make sure the answer (der_1) is formatted in matrix form as in the picture shown, likewise how to turn a normal linear formula into matrix form, if i was give one however in the right position. stiffness matrix

from sympy import *

import sympy as sy
# Create the displacements symbols
u_1 ,u_2 , u_3 ,u_4= sy.symbols('u_1 u_2 u_3 u_4')
# Create the force symbols 
f_1 ,f_2 , f_3 ,f_4= sy.symbols('f_1 f_2 f_3 f_4')
# Create the constant of k
k_1 ,k_2 ,k_3 ,k_4= sy.symbols('k_1 k_2 k_3 k_4')
# Define minimum potential energy
U_internal= 0.5*k_1*(u_1 - u_3)**2 + 0.5*k_2*(u_3 - u_4)**2 + 0.5*k_3*(u_4 - u_2)**2

O_potential = (-f_1*u_1 - f_2*u_2 - f_3*u_3 - f_4*u_4)

potential_energy = U_internal + O_potential

der_1 = potential_energy.diff(u_1)

print(der_1)
1

There are 1 best solutions below

2
Oscar Benjamin On

I think what you're looking for is the Hessian matrix:

In [4]: hessian(potential_energy, [u_1, u_2, u_3, u_4])
Out[4]: 
⎡1.0⋅k₁      0         -1.0⋅k₁             0       ⎤
⎢                                                  ⎥
⎢   0     1.0⋅k₃          0             -1.0⋅k₃    ⎥
⎢                                                  ⎥
⎢-1.0⋅k₁     0     1.0⋅k₁ + 1.0⋅k₂      -1.0⋅k₂    ⎥
⎢                                                  ⎥
⎣   0     -1.0⋅k₃      -1.0⋅k₂      1.0⋅k₂ + 1.0⋅k₃⎦

Note that if you use exact rational numbers Rational(1, 2) or S(1)/2 then you can get an exact result. You can also convert the floats to Rational with nsimplify:

In [5]: nsimplify(_)
Out[5]: 
⎡k₁    0     -k₁       0   ⎤
⎢                          ⎥
⎢ 0   k₃      0       -k₃  ⎥
⎢                          ⎥
⎢-k₁   0   k₁ + k₂    -k₂  ⎥
⎢                          ⎥
⎣ 0   -k₃    -k₂    k₂ + k₃⎦