Inverse Matrix in Python
The problem:
A group comprised of kids and adults took the metro to a baseball game. The cost of transportation to go was \$3 per child and \$3.20 per adult for a total cost of \$118.40. The game was a bit boring so the group ended up taking the bus home which would get them home sooner. The cost of the bus was \$3.50 per child and \$3.60 per adult for a total of \$135.20.
How many kids and adults were in the group?
This is basically a 2 x 2 Linear System set of equations.
Two equations, two unknowns:
$$x_1 * m_k + x_2 * m_a = m_{total}$$
$$x_1 * b_k + x_2 * b_a = b_{total}$$
Or we could try it with linear algebra.
Linear Algebra
$$ \begin{pmatrix} {a_{11}} & {a_{21}} \cr {a_{21}} & {a_{22}} \end{pmatrix} * \begin{pmatrix} {x_1} \cr {x_2} \end{pmatrix} = \begin{pmatrix} {y_1} \cr {y_2} \end{pmatrix} $$
Now the challenge with the llinear algebra equation is that we need to solve for $x_1$ and $x_2$. To do that we would divide each side by the fare matrix. However matrices aren’t communative so the recommended way to solve is to multiply against the inverted matrices.
$$ \begin{pmatrix} {x_1} \cr {x_2} \end{pmatrix} = \begin{pmatrix} {y_1} \cr {y_2} \end{pmatrix} * \begin{pmatrix} {a_{11}} & {a_{21}} \cr {a_{21}} & {a_{22}} \end{pmatrix}^{-1} $$
The following is my code to solve utilizing linear algebra.
import numpy as np
from numpy.linalg import inv
#Set up the fares matrix (a_11, a_12 etc)
fare_costs = np.array([[3.0, 3.5], [3.2, 3.6]])
fare_costs
array([[3. , 3.5],
[3.2, 3.6]])
We are using numpy to create the matrix. Be mindful of the shape of the array as it needs to have the proper dimensions. In this example we have 2x2 and 2x1 matrices.
fare_costs.shape
(2, 2)
total = np.array([
[118.4],
[135.2]
])
total.shape
(2, 1)
# Take the inverse of fare_costs and multiple it by the total costs and then sum across each row.
# We then reshape the array from 1 dimension (2,) to (2,1) to reflect a column vector per the equation.
(inv(fare_costs) * total).sum(axis=0).reshape((2,1))
array([[16.],
[22.]])
The answer for $x_1$ and $x_2$ are 16 kids and 22 adults.
reference to original example: https://www.mathsisfun.com/algebra/matrix-inverse.html