Python:Matrices

From AIMSWiki

Table of contents


The Numeric module (you can also use scipy) in Python allows you to work with matrices and vectors. The following is a list of some useful commands and functions for creating and manipulating matrices. The following assumes that you have

from scipy import *

in your program.

Creating matrices and vectors

You can enter a matrix as a list of lists. The values in the matrix are usually entered row by row.

A = mat([[0, 5, 2, 6, 3], [2, 6, 3, 5, 2], [8, 4, 4, 2, 1]])

This matrix has 3 rows and 5 columns. Note that you should make sure that you have the same number of columns in each row to avoid problems.

You can also use the Octave (and Matlab) notation to enter a matrix.

A = mat('[0, 5, 2, 6, 3; 2, 6, 3, 5, 2; 8, 4, 4, 2, 1]')

Note that a string is sent as parameter to mat. Python will give an error message otherwise, seeing as the syntax inside the string does not conform to normal Python syntax.

  • Do not leave a space after the first square bracket or before the last one. This causes an error for some obscure reason. The error message will read SyntaxError: unexpected EOF while parsing.

There are some other functions to create special types of matrices or vectors.

zeros([rows, columns])

Create a matrix of zeros

empty([rows, columns])

Create an uninitialized matrix. Uninitialized means that the values in the matrix could be anything (not necessarily zero, for example). This is much faster that the zeros function.

linspace(a, b)
linspace(a, b, n)

Create a vector of linearly spaced values starting from a and ending at b. This optional argument n specifies the number of values to generate (default: 50).

logspace(a, b)
logspace(a, b, n)

Create a vector of exponentially spaced values starting from 10**a and ending at 10**b. This optional argument n specifies the number of values to generate (default: 50).

eye(N)
eye(N, M)

Create an N×N or N×M identity matrix.

diag(x)
diag(x, k)
  • If x is a matrix: returns a vector containing the diagonal of x
  • If x is a vector: returns a matrix with x as the diagonal
  • k can be used to choose which diagonal the extract or create.

Selecting rows or columns

>>> A[0:2, 2:5]      # Select the rows 0, 1 and columns 2, 3, 4
array([[2, 6, 3],
       [3, 5, 2]])

>>> A[:, 0]          # Select all the rows and column 0
array([0, 2, 8])

>>> A[:, 0::2]       # Select all the rows and columns 0, 2, 4
array([[5, 6],
       [6, 5],
       [4, 2]])
>>> take(A, [0, 2])              # Select rows 0, 2
array([[0, 5, 2, 6, 3],
       [8, 4, 4, 2, 1]])

>>> take(A, [0, 2], axis = 1)    # Select columns 0, 2
array([[0, 2],
       [2, 3],
       [8, 4]])

Stacking matrices

You can combine existing matrices or vectors into larger matrices. This is called stacking.

vstack(tup)
  • Stacks matrices vertically (row on row).
  • tup is a tuple of matrices to stack.
>>> A = mat('[1, 2, 3]')
>>> B = mat('[4, 5, 6; 7, 8, 9]')
>>> print vstack((A, B))
[[1 2 3]
 [4 5 6]
 [7 8 9]]
hstack(tup)
  • Stacks matrices horizontally (column on column)
  • tup is a tuple of matrices to stack.
>>> A = mat('[1, 2, 3]')
>>> B = mat('[4, 5, 6]')
>>> print hstack((A, B))
[ [1 2 3 4 5 6]]

Element operations

There is an important difference between the Matrix type and the array type. The Matrix type does not allow element by element operations as readily as the array type does.

You can add (+), subtract (-), multiply (*), divide (/ or //), take powers of (**) and find remainders of (%) elements by using the array type. For example,

>>> A = array([[1, 2, 3], [4, 5, 6]])
>>> B = array([[7, 8, 9], [0, 1, 2]])
>>> A * B
array([[ 7, 16, 27],
       [ 0,  5, 12]])

This does not calculate the matrix product. Rather, it multiplies each element in A with its corresponding element in B.

Note that this does not work with the Matrix type.

>>> A = mat([[1, 2, 3], [4, 5, 6]])
>>> B = mat([[7, 8, 9], [0, 1, 2]])
>>> A * B
ValueError: matrices are not aligned

You get an error because the inner matrix dimensions do not match.

Another time when the type is important, is when calculating powers (**). If the type is Matrix, Python will compute the power of the matrix, if the type is array, the power of each element inside the matrix. For example

>>> A = eye(3)
>>> B = mat(A)

A is now an array and B a Matrix representing the 3×3 identity matrix.

>>> A ** -1
array([[  1., inf, inf],
       [ inf,  1., inf],
       [ inf, inf,  1.]])

Note the infinities originating from dividing by 0. This was an element by element operation.

>>> B ** -1
Matrix([[ 1.,  0.,  0.],
        [ 0.,  1.,  0.],
        [ 0.,  0.,  1.]])

This is the inverse of the identity matrix. This was a matrix operation.

Operations and functions

transpose(A)

Matrix transpose.

trace(A)

The trace (meaning the sum of the diagonal elements) of the matrix.

sum(x)
prod(x)

The sum/product of the elements in a vector.

Linear Algebra

For more complicated matrix operations and functions, like finding eigenvalues and determinants or solving systems of linear equations, have a look at the Linear Algebra module of SciPy.


Return to the Python index