top of page
Search

# Matrix Solution in Python's Numpy

Updated: Sep 10 A matrix in mathematics is an array, in a program containing numbers, alphanumerics or variables in 1-dimensional, 2-dimensional or 3-dimensional formats. These arrays can be used in many situations to hold unique or repetitive data.

To the computer, the array stores data. To the mathematician, however, the array is a matrix of variables. In the simplest form, the array can be used to contain the data of the coefficients of variables of an equation.

This array can be used to solve a series of simultaneous equations. For starters, we shall start with solving a system of two and three variables. This method may, however, be scaled to solve systems of over a hundred variables.

An example of a set of two simultaneous equations solved using Python has been demonstrated below.

```z=3*x + 4*y
z'=2*x + 7*y```

These are the two equations that we shall be solving. The simplest mathematical method is to just multiply coefficients and subtract equations, then solve for variable 'x' and subsequently substitute to solve for variable 'y'.

This solution is possible for up to five variables in a single equation, and for up to 5 equations. This method gradually increases difficulty with the number of variables in a single equation.

Thus, we can use the matrix method to solve equations with nearly a hundred variables or more.

Let us look at the above equations in matrix form.

```Matrix M =
[[3 4]
[2 7]]```

This is the matrix that we call the coefficient matrix, which contains the coefficients of the variables, x and y. The other matrix required is the solution matrix, containing values of z and z'. For this problem, we are setting the values of z and z' to be 10 and 34.

```Matrix Z =
[
]```

Let the variable matrix be called X for our reference. If we are to solve it as a matrix, we now get two equations of three variables as a single equation of three variables.

```M.X=Z
X=M^(-1).Z```

Where M^(-1) is the inverse of matrix M.

The solution for this system of linear equations was performed in Python using the following code.

```from numpy import *

M=array([[3, 4], [2, 7]])
Z=array([, ])
print(f"Coefficient matrix M = \n {M}")
print(f"Solution matrix Z = \n {Z}")
X=linalg.solve(M,Z)
print(f"Final solution in variable matrix X = \n {X}")```

Numpy's linear algebra package uses the above inverse multiplication method in the linalg.solve() function.

```Coefficient matrix M =
[[3 4]
[2 7]]
Solution matrix Z =
[
]
Final solution in variable matrix X =
[[-5.07692308]
[6.30769231]]```

#Issue8