Skip to main content

Matrix Operations using Python



What You will Learn

  • You will learn to create matrices
  • You will learn to solve linear equations by computing the inverse of a matrix.
  • You will learn to compute the eigen values of a matrix

Matrices using Python

A $5\times 3$ matrix is created, printed and displayed as an image using the code below. Its transpose is generated by the $transpose()$ function.
from scipy import *
from pylab import *
x=mat([[1,2,3,4,5],[4,5,6,9,15],[7,8,9,23,25]])
print x
print shape(x)
print transpose(x)
matshow(x)
show()

Solution of Linear Equations

Linear systems are represented by matrix equations. See the electrical network in the figure below. All resistances are in $\Omega$. The network is described by the set of equations. \begin{equation} 9I_{1}-4 I_{2}=20 \end{equation} \begin{equation} -4I_{1}-6 I_{2}=-10 \end{equation} \begin{equation} 8I_{3}-3 I_{4}=-20 \end{equation} \begin{equation} -3I_{3}+7 I_{4}=10 \end{equation}
Or as a matrix-vector product as \begin{equation} \begin{bmatrix} \phantom{-}9&-4&\phantom{-}0&\phantom{-}0\\ -4&\phantom{-}6&\phantom{-}0&\phantom{-}0\\ \phantom{-}0&\phantom{-}0&\phantom{-}8&-3\\ \phantom{-}0&\phantom{-}0&-3&\phantom{-}7\\ \end{bmatrix} \begin{bmatrix} I_{1}\\ I_{2}\\ I_{3}\\ I_{4}\\ \end{bmatrix} = \begin{bmatrix} \phantom{-}20\\ -10\\ -20\\ \phantom{-}10\\ \end{bmatrix} \end{equation} We will get the solution for currents if we pre-multiply this equation with inverse of the resistance matrix. The following yields the solution for currents.
from scipy import *
import scipy.linalg as lin
rmat=mat([[9,-4,0,0],[-4,6,0,0],[0,0,8,-3],[0,0,-3,7]])
sourcevect=mat([20,-10,-20,10])
Ivect=lin.inv(rmat)*transpose(sourcevect)
print Ivect
When run the code prints the current values as $I_{1}=2.10526316$, $I_{2}=-0.26315789$, $I_{3}=-2.34042553$ and $I_{4}=0.42553191$.

Eigen Values of a Matrix

Let us look at the matrix equation \begin{equation} [\mathbf{A}][\mathbf{X}]=[\mathbf{b}] \end{equation} where $\mathbf{A}$ is an $N\times$ matrix and $\mathbf{X}$ and $\mathbf{b}$ are $N\times 1$ vectors. It is not necessary that the vectors $\mathbf{X}$ and $\mathbf{b}$ need not be in the same direction. Let us look into this with $N=2$. Let $\mathbf{A}=\begin{bmatrix} 1 & 2\\3&4\\ \end{bmatrix}$ and the vector $\mathbf{X}=\begin{bmatrix}\phantom{-}1\\ -1\\ \end{bmatrix}$ making the vector $\mathbf{b}=\begin{bmatrix}-1\\ -1\\ \end{bmatrix}$. the two vectors $\mathbf{X}$ and $\mathbf{b}$ are plotted along the orthogonal coordinates $x_1$ and $x_2$ as shown in the figure below. You can see that they are in different directions.
For $\mathbf{b}$ or $\mathbf{A}\mathbf{X}$ to be in the direction of $\mathbf{X}$ \begin{equation} [\mathbf{A}][\mathbf{X}]=\lambda [\mathbf{X}] \end{equation} where $\lambda$ is a constant. Transposing this equation, gets \begin{equation} [\mathbf{A}-\lambda \mathbf{I}][\mathbf{X}]=[\mathbf{0}] \end{equation} $\mathbf{X}=\mathbf{0}$ is a trivial solution which makes \begin{equation} [\mathbf{A}-\lambda \mathbf{I}]=[\mathbf{0}] \end{equation} or \begin{equation} |\mathbf{A}-\lambda \mathbf{I}|=0 \end{equation} where $\mathbf{I}$ is the $N\times 1$ identity matrix. The above eaquation is called the characterstic equation and the solutions for $\lambda$ are called eigen values of the matrix $\mathbf{A}$ . The vectors $\lambda \mathbf{X}$ are called eigenvectors. See the red colored vector in the above figure. Eigen values and vectors are useful in trend analysis and reduction of dimensionality of data. the eigen values of the above resistance matrix is computed with the following code.
from scipy import * import numpy.linalg as lin
rmat=mat([[9,-4,0,0],[-4,6,0,0],[0,0,8,-3],[0,0,-3,7]])
eig_vals=lin.eig(rmat)
print eig_vals[0]
print eig_vals[1]
print "The rank of the matrix is " + repr(lin.matrix_rank(rmat))
The eig module in linalg computes the eigen values and normalized eigen vectors and returns as two arrays. eig_vals[0] contains the eigen values as $[ 11.77200187+0.j 3.22799813+0.j 10.54138127+0.j 4.45861873+0.j]$. eig_vals[1] contains the corresponding normalized eigen vectors. Here they are $[ 0.82192562 0.56959484 0. 0. ]$, $[-0.56959484 0.82192562 0. 0. ]$, $ [ 0. 0. 0.76301998 0.6463749 ]$ and $ [ 0. 0. -0.6463749 0.76301998]$ respectively. The matrix_rank module returns the rank of the matrix.

What You Learned

  • You learned to create matrices
  • You solved linear equations by computing the inverse of a matrix.
  • You computed the eigen values and rank of a matrix

Comments

Popular posts from this blog

Overview of Scientific Computing

Introduction Scientific computing broadly means computations carried out for scientific or engineering needs. This mostly includes processing of large arrays or matrices, plotting of functions, solving equations, performing mathematical transforms etc very fast while keeping programming hassles at a minimum. Requirements of Scientific Computing The language for scientific computing should be Interpreted should be modular should have easy routines for array, matrix and vectors should have a publication quality plotting library Python for Scientific Computing Python is an interpreted, modular language that is suitable for scientific computing. Modules such as numpy, scipy etc provide many scientific computing tools. The module matpplotlib alias pylab provides publication quality plotting libraries. Python 2.7 and Python 3 are available in all major Linux distros and can be installed as bundle such as anaconda in Windows. An enhanced Python shell ipython...

Lists, Arrays and Matrices and their Visualization

What You Will Learn You will create lists, arrays and matrices using scipy You will learn to slice, reverse, append and plot arrays Lists in Python Type in the code at the Ipython console from scipy import * x=[1,2,3,4,5] The first line imports all modules in scipy. The second line creates a list in the variable x. Type x at the console and observe the list Type x[0:2] at the console and observe the first two values in the list Type x[3:5] at the console and observe a slice of the list Type x[::-1] at the console and observe the reversed list Type len(x) at the console and observe the length of the list x Type y=[4,5,6] and then type x+y observe the two lists getting concatenated. Type append(x,y) observe a similar result Type z=['apple','orange','pear'] to create a list of strings Arrays using Scipy scipy and numpy provide arrays that support mathematical operations. Type x=array([1,2,3,4,5]) at the cons...

Functions in Python

Functions in Python Dr. Hari V S Department of Electronics and Communication College of Engineering Chengannur What You will Learn You will learn the syntax of Python functions You will learn to import the functions to other codes The Syntax The syntax used the keyword $def$ followed the name of the function again followed by a colon (:) that is then followed by an indented code block of instructions. The function def function_name(arg1.arg2,....argN): statements return results A Simple Python Function Needless to say that the statements and the return command should form an indented block. Consider a simple function that returns the sum of the input values. It is realized as the function below. def summ(x,y): return x+y Unlike MATLAB or IDL, it is possible to execute a function in the Python shell. You may type the above function in a Python shell or an enhanced Python shell such as IPython. Once the ...