Contact Us!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

| Download
Views: 37
Visibility: Unlisted (only visible to those who know the link)
Image: ubuntu2204
Kernel: Python 3 (system-wide)

Matrix solution for a set of linear equations

It can be tedious to solve a set of three or more linear equations. However, the equations can be rewritten in matrix form and solved computationally. Suppose that you want to solve the equations

50I1+180I2=25,10I1+100I290I3=0,40I1+200I3=25.50 I_1 +180 I_2 = 25, \\ 10 I_1 + 100 I_2 - 90 I_3 = 0, \\ 40 I_1 + 200 I_3 = 25.

These equations can be rewritten as

[5018001010090400200][I1I2I3]=[25025].\left[ \begin{array}{ccc} 50 & 180 & 0 \\ 10 & 100 & -90 \\ 40 & 0 & 200 \end{array} \right] \left[ \begin{array}{c} I_1 \\ I_2 \\ I_3 \end{array} \right] = \left[ \begin{array}{c} 25 \\ 0 \\ 25 \end{array} \right].

Define the matrices

a=[5018001010090400200],a = \left[ {\begin{array}{ccc} 50 & 180 & 0 \\ 10 & 100 & -90 \\ 40 & 0 & 200\\ \end{array} } \right],
x=[I1I2I3],x = \left[ {\begin{array}{cc} I_1 \\ I_2 \\ I_3 \\ \end{array} } \right],

and

b=[25025].b = \left[ {\begin{array}{cc} 25 \\ 0 \\ 25 \\ \end{array} } \right].

We must solve the following matrix equation

ax=bax = b

for xx. If the multiplicative inverse of the matrix aa is a1a^{-1}, then the solution is

x=a1b.x = a^{-1}b.

It is easy to find the solution with numpy as shown below. If the two objects being multiplied are matrices, the multiplication operator (*) performs matrix multiplication. Documentation of the matrix class is available at http://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html.

import numpy as np a = np.matrix([[50, 180, 0], [10, 100, -90], [40, 0, 200]]) b = np.matrix([[25], [0], [25]]) # a.I is the multiplicative inverse of the matrix a x = (a.I)*b print(x)
[[-11.875 ] [ 3.4375] [ 2.5 ]]

This means that

I1=11.875,I2=3.4375,I3=2.5.I_1 = -11.875, \\ I_2 = 3.4375, \\ I_3 = 2.5.

If the equations to be solved involve physical quantities, you must keep track of units. In that case, it is best to convert all quantities to standard units so that the results will be in standard units. If there is no solution to the equations, the matrix inversion will result in an error.

Alternately, the linear algebra solver in scipy can be used. Documentation is at https://docs.scipy.org/doc/scipy/reference/linalg.html.

import scipy.linalg as spl print(spl.solve(a,b))
[[-11.875 ] [ 3.4375] [ 2.5 ]]