You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 29 Next »

The NumPy library is very helpful for solving linear systems in Python. For instructions on how to install NumPy look here.

Page content

Matrixes in Python

Like many other programming languages, the indices in Python arrays starts at 0. This is commonly known, but may catch you by surprise if you're used to the indices in e.g. Matlab.


In Python, matrices are not it's own thing, but rather a list of list/nested lists. Let's look at an example:

Our matrix of choice will be To represent this matrix in python, we will consider the matrix as two independent lists,  and , put together in one list. Written in code, it looks like this:

mat1 = [[1, 2, 3], [4, 5, 6]]
# To make the matrices easier to read while coding, we can place the different lists vertical to eachother instead of horizontally.
mat2 = [[1, 2, 3],
	   [4, 5, 6]]

# Printing both of these matrices will result in the same output:
[[1, 2, 3], [4, 5, 6]]

# To alter the output to a more readable format, for-loops are very helpful:
[[1, 2, 3], 
[4, 5, 6]]

Now, let's see how to obtain different values from our matrix:

A = [[1, 2, 3], 
	[4, 5, 6]]

print("A =", A) 
print("A[1] =", A[1])      		# 2nd row
print("A[1][2] =", A[1][2])   	# 3rd element of 2nd row
print("A[0][-1] =", A[0][-1])   # Last element of 1st Row

column = [];        			# Empty list
for row in A:
  column.append(row[2])   		# Adding the element in the third column of every row-list.

print("3rd column =", column)

The script above will result in the following output:

A = [[1, 2, 3], [4, 5, 6]]
A[1] = [4, 5, 6]
A[1][2] = 6
A[0][-1] = 3
3rd column = [3, 6]

Matrixes in Python using NumPy


Creating a matrix
a = np.array([[1,2],[3,4]])

In Python rows and columns start at 0. For example index the data at first row second column : 

Indexing matrix
b = a[0,1]


Linear algebra using NumPy

NumPy has several useful functions for linear algebra built-in. For full list look check the NumPy documentation.


Solve()
np.linalg.solve(a,b) #where a and b is matrixs


#returns a array with solutions to the system


Eigenvalues and eigenvectors
np.linalg.eig(a) # where a is a square matrix


#returns two arrays [v,w]
#v containing the eigenvalues of a
#w containing the eigenvectors of a


Determinant
np.linalg.det(a) # where a is a square matrix


#returns the determinant of the matrix a
Finding the inverse
np.linalg.inv(a) # where a is the matrix to be inverted


#Returns the inverse matrix of a

Example

Solving set of equations
import numpy as np

# Solving following system of linear equation
# 5a + 2b = 35
# 1a + 4b = 49

a = np.array([[5, 2],[1,4]]) # Lefthand-side of the equation
b = np.array([35, 94]) #Righthand-side

print(np.linalg.solve(a,b)) #Printing the solution


Relaterte artikler



  • No labels