Linear algebra formulation
Bringing back optimization
Someone provided us with 6 weights and 3 rods. We need to calculate the positions of suspension points to have a balanced system.
If the system is in equilibrium, torque must be zero at every pivot point
Let’s define and
We need 3 more equations. Let’s constrain the length of every rod
Bold marks matrices. Vector such as and are matrices too (1D).
Python has a lot of built-in functions to solve problems in this form
Analytical solution exists only if
Remember that , where is the unity matrix.
Python’s straight forward implementation (not the fastest)
import numpy as np
# define A and B marices
invA = np.linalg.inv(A)
# Pay attention @ is not the same as *
# @ also is matrix multiplication by Linear Algebra rules
# * is the element wise multiplication
x = invA @ B
Inverting matrix is computationally expensive!
Python’s faster way by using equation solver directly (recommended)
import numpy as np
# define A and B marices
invA = inv(A)
x = np.linalg.solve(A, B)
import numpy as np
A = np.array([[ 2, 3], [5, 1]])
B = np.array([[8], [7]])
invA = np.linalg.inv(A)
x = invA @ B
In [9]: invA
Out[9]:
array([[-0.07692308, 0.23076923],
[ 0.38461538, -0.15384615]])
In [10]: x
Out[10]:
array([[1.],
[2.]])
import numpy as np
A = np.array([[ 2, 3], [5, 1]])
B = np.array([[8], [7]])
x = np.linalg.solve(A, B)
In [12]: x
Out[12]:
array([[1.],
[2.]])
# check
In [15]: A @ x
Out[15]:
array([[8.],
[7.]])
If , , , , , , , , and , then and .
import numpy as np
A=np.array([
[20, -20, 0, 0, 0, 0],
[0, 0, 3, -12, 0, 0],
[0, 0, 0, 0, 2, -3],
[1, 1, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 1, 1],
])
B= np.array([[0], [0], [0], [2], [1], [3] ])
x=np.linalg.inv(A) @ B
In [33]: x
Out[33]:
array([[1. ],
[1. ],
[0.8],
[0.2],
[1.8],
[1.2]])
Check
In [32]: A @ x - B
Out[32]:
array([[0.0000000e+00],
[0.0000000e+00],
[0.0000000e+00],
[0.0000000e+00],
[0.0000000e+00],
[4.4408921e-16]])
Solutions based on the inverse matrix calculation involve extra steps (unnecessary for solution) and, thus, are slower
However, it is handy to calculate the inverse matrix in advance if you solve for different with the same .
We can say that
is equivalent to
find which minimizes
In python it can be done via
import numpy as np
A = np.array([[ 2, 3], [5, 1]])
B = np.array([[8], [7]])
sol = np.linalg.lstsq(A, B)
x = sol[0]
In [40]: x
Out[40]:
array([[1.],
[2.]])
Sounds useless but it allows to solve over constrained problems like
Very common in physics. Mentally replace
import numpy as np
A=np.array([ [4], [5] ])
B=np.array([ [3], [2] ])
sol = np.linalg.lstsq(A, B)
x = sol[0]
In [44]: x
Out[44]: array([[0.53658537]])