Chapter 3
Arrays and Matrices
In the previous chapter, we have learned the essential features of Python language. We also used the math
module to calculate trigonometric functions. Using the tools introduced so far, let us generate the data points
to plot a sine wave. The program sine.py generates the coordinates to plot a sine wave.
Example sine.py
import math
x = 0.0
while x < 2 * math.pi:
print x , math.sin(x)
x = x + 0.1
The output to the screen can be redirected to a le as shown below, from the command prompt. You can plot
the data using some program like xmgrace.
$ python sine.py > sine.dat
$ xmgrace sine.dat
It would be better if we could write such programs without using loops explicitly. Serious scientic computing
requires manipulating of large data structures like matrices. The list data type of Python is very exible but
the performance is not acceptable for large scale computing. The need of special tools is evident even from the
simple example shown above. NumPy is a package widely used for scientic computing with Python.
1
3.1 The NumPy Module
The numpy module supports operations on compound data types like arrays and matrices. First thing to learn
is how to create arrays and matrices using the numpy package. Python lists can be converted into multi-
dimensional arrays. There are several other functions that can be used for creating matrices. The mathematical
functions like sine, cosine etc. of numpy accepts array objects as arguments and return the results as arrays
objects. NumPy arrays can be indexed, sliced and copied like Python Lists.
In the examples below, we will import numpy functions as local (using the syntax from numpy import * ).
Since it is the only package used there is no possibility of any function name conicts.
Example numpy1.py
from numpy import *
x = array( [1, 2, 3] ) # Make array from list
print x , type(x)
In the above example, we have created an array from a list.
3.1.1 Creating Arrays and Matrices
We can also make multi-dimensional arrays. Remember that a member of a list can be another list. The
following example shows how to make a two dimensional array.
Example numpy3.py
1 http://numpy.scipy.org/
http://www.scipy.org/Tentative_NumPy_Tutorial
http://www.scipy.org/Numpy_Functions_by_Category
http://www.scipy.org/Numpy_Example_List_With_Doc
35
CHAPTER 3. ARRAYS AND MATRICES 36
from numpy import *
a = [ [1,2] , [3,4] ] # make a list of lists
x = array(a) # and convert to an array
print a
Other than than array(), there are several other functions that can be used for creating dierent types of arrays
and matrices. Some of them are described below.
3.1.1.1 arange(start, stop, step, dtype = None)
Creates an evenly spaced one-dimensional array. Start, stop, stepsize and datatype are the arguments. If
datatype is not given, it is deduced from the other arguments. Note that, the values are generated within the
interval, including start but excluding stop.
arange(2.0, 3.0, .1) makes the array([ 2. , 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9])
3.1.1.2 linspace(start, stop, number of elements)
Similar to arange(). Start, stop and number of samples are the arguments.
linspace(1, 2, 11) is equivalent to array([ 1. , 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. ])
3.1.1.3 zeros(shape, datatype)
Returns a new array of given shape and type, lled zeros. The arguments are shape and datatype. For example
zeros( [3,2], 'oat') generates a 3 x 2 array lled with zeros as shown below. If not specied, the type of elements
defaults to int.
0.0 0.0 0.0
0.0 0.0 0.0
3.1.1.4 ones(shape, datatype)
Similar to zeros() except that the values are initialized to 1.
3.1.1.5 random.random(shape)
Similar to the functions above, but the matrix is lled with random numbers ranging from 0 to 1, of oat type.
For example, random.random([3,3]) will generate the 3x3 matrix;
array([[ 0.3759652 , 0.58443562, 0.41632997],
[ 0.88497654, 0.79518478, 0.60402514],
[ 0.65468458, 0.05818105, 0.55621826]])
3.1.1.6 reshape(array, newshape)
We can also make multi-dimensions arrays by reshaping a one-dimensional array. The function reshape()
changes dimensions of an array. The total number of elements must be preserved. Working of reshape() can be
understood by looking at reshape.py and its result.
Example reshape.py
from numpy import *
a = arange(20)
b = reshape(a, [4,5])
print b
The result is shown below.
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
The program numpy2.py demonstrates most of the functions discussed so far.
Example numpy2.py
CHAPTER 3. ARRAYS AND MATRICES 37
from numpy import *
a = arange(1.0, 2.0, 0.1)
print a
b = linspace(1,2,11)
print b
c = ones(5,'float')
print c
d = zeros(5, 'int')
print d
e = random.rand(5)
print e
Output of this program will look like;
[ 1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9]
[ 1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2. ]
[ 1. 1. 1. 1. 1.]
[ 0. 0. 0. 0. 0.]
[ 0.89039193 0.55640332 0.38962117 0.17238343 0.01297415]
3.1.2 Copying
Numpy arrays can be copied using the copy method, as shown below.
Example array_copy.py
from mumpy import *
a = zeros(5)
print a
b = a
c = a.copy()
c[0] = 10
print a, c
b[0] = 10
print a,c
The output of the program is shown below. The statement b = a does not make a copy of a. Modifying b aects
a, but c is a separate entity.
[ 0. 0. 0.]
[ 0. 0. 0.] [ 10. 0. 0.]
[ 10. 0. 0.] [ 10. 0. 0.]
3.1.3 Arithmetic Operations
Arithmetic operations performed on an array is carried out on all individual elements. Adding or multiplying
an array object with a number will multiply all the elements by that number. However, adding or multiplying
two arrays having identical shapes will result in performing that operation with the corresponding elements. To
clarify the idea, have a look at aroper.py and its results.
Example aroper.py
from numpy import *
a = array([[2,3], [4,5]])
b = array([[1,2], [3,0]])
print a + b
print a * b
The output will be as shown below
array([[3, 5],
[7, 5]])
array([[ 2, 6],
[12, 0]])
Modifying this program for more operations is left as an exercise to the reader.
CHAPTER 3. ARRAYS AND MATRICES 38
3.1.4 cross product
Returns the cross product of two vectors, dened by
i j k
A×B = A1 A2 A3 = i(A2 B3 − A3 B2 ) + j(A1 B3 − A3 B1 ) + k(A1 B2 − A2 B1 ) (3.1)
B1 B2 B3
It can be evaluated using the function cross((array1, array2). The program cross.py prints [-3, 6, -3]
Example cross.py
from numpy import *
a = array([1,2,3])
b = array([4,5,6])
c = cross(a,b)
print c
3.1.5 dot product
Returns the dot product of two vectors dened by A.B = A1 B1 + A2 B2 + A3 B3 . If you change the fourth line
of cross.py to c = dot(a, b), the result will be 32.
3.1.6 Saving and Restoring
An array can be saved to text le using array.tole(lename) and it can be read back using array=fromle()
methods, as shown by the code leio.py
Example leio.py
from numpy import *
a = arange(10)
a.tofile('myfile.dat')
b = fromfile('myfile.dat',dtype = 'int')
print b
The function fromle() sets dtype='oat' by default. In this case we have saved an integer array and need to
specify that while reading the le. We could have saved it as oat the the statement a.tole('myle.dat', 'oat').
3.1.7 Matrix inversion
The function linalg.inv(matrix) computes the inverse of a square matrix, if it exists. We can verify the result
by multiplying the original matrix with the inverse. Giving a singular matrix as the argument should normally
result in an error message. In some cases, you may get a result whose elements are having very high values, and
it indicates an error.
Example inv.py
from numpy import *
a = array([ [4,1,-2], [2,-3,3], [-6,-2,1] ], dtype='float')
ainv = linalg.inv(a)
print ainv
print dot(a,ainv)
Result of this program is printed below.
[[ 0.08333333 0.08333333 -0.08333333]
[-0.55555556 -0.22222222 -0.44444444]
[-0.61111111 0.05555556 -0.38888889]]
[[ 1.00000000e+00 -1.38777878e-17 0.00000000e+00]
[-1.11022302e-16 1.00000000e+00 0.00000000e+00]
[ 0.00000000e+00 2.08166817e-17 1.00000000e+00]]
Chapter 4
Data visualization
A graph or chart is used to present numerical data in visual form. A graph is one of the easiest ways to compare
numbers. They should be used to make facts clearer and more understandable. Results of mathematical
computations are often presented in graphical format. In this chapter, we will explore the Python modules used
for generating two and three dimensional graphs of various types.
4.1 The Matplotlib Module
Matplotlib is a python package that produces publication quality gures in a variety of hardcopy formats. It
also provides many functions for matrix manipulation. You can generate plots, histograms, power spectra,
bar charts, error-charts, scatter-plots, etc, with just a few lines of code and have full control of line styles, font
properties, axes properties, etc. The data points to the plotting functions are supplied as Python lists or Numpy
arrays.
If you import matplotlib as pylab, the plotting functions from the submodules pyplot and matrix manipu-
lation functions from the submodule mlab will be available as local functions. Pylab also imports Numpy for
you. Let us start with some simple plots to become familiar with matplotlib.
1
Example plot1.py
from pylab import *
data = [1,2,5]
plot(data)
show()
In the above example, the x-axis of the three points is taken from 0 to 2. We can specify both the axes as shown
below.
Example plot2.py
from pylab import *
x = [1,2,5]
y = [4,5,6]
plot(x,y)
show()
By default, the color is blue and the line style is continuous. This can be changed by an optional argument after
the coordinate data, which is the format string that indicates the color and line type of the plot. The default
format string is `b-` (blue, continuous line). Let us rewrite the above example to plot using red circles. We will
also set the ranges for x and y axes and label them.
Example plot3.py
from pylab import *
x = [1,2,5]
y = [4,5,6]
plot(x,y,'ro')
xlabel('x-axis')
ylabel('y-axis')
axis([0,6,1,7])
show()
40
CHAPTER 4. DATA VISUALIZATION 41
Figure 4.1: Output of (a) plot4.py (b) subplot1.py (c) piechart.py
The gure 4.1 shows two dierent plots in the same window, using dierent markers and colors.
Example plot4.py
from pylab import *
t = arange(0.0, 5.0, 0.2)
plot(t, t**2,'x') # t2
plot(t, t**3,'ro') # t3
show()
We have just learned how to draw a simple plot using the pylab interface of matplotlib.
4.1.1 Multiple plots
Matplotlib allows you to have multiple plots in the same window, using the subplot() command as shown in
the example subplot1.py, whose output is shown in gure 4.1(b).
Example subplot1.py
from pylab import *
subplot(2,1,1) # the first subplot
plot([1,2,3,4])
subplot(2,1,2) # the second subplot
plot([4,2,3,1])
show()
The arguments to subplot function are NR (number of rows) , NC (number of columns) and a gure number,
that ranges from 1 to N R ∗ N C. The commas between the arguments are optional if N R ∗ N C < 10, ie.
subplot(2,1,1) can be written as subplot(211).
Another example of subplot is given is subplot2.py. You can modify the variable NR and NC to watch the
results. Please note that the % character has dierent meanings. In (pn+1)%5, it is the reminder operator
resulting in a number less than 5. The % character also appears in the String formatting.
Example subplot2.py
from pylab import *
mark = ['x','o','^','+','>']
NR = 2 # number of rows
NC = 3 # number of columns
pn = 1
for row in range(NR):
for col in range(NC):
subplot(NR, NC, pn)
a = rand(10) * pn
plot(a, marker = mark[(pn+1)%5])
xlabel('plot %d X'%pn)
ylabel('plot %d Y'%pn)
pn = pn + 1
show()
1 http://matplotlib.sourceforge.net/
http://matplotlib.sourceforge.net/users/pyplot_tutorial.html
http://matplotlib.sourceforge.net/examples/index.html
http://matplotlib.sourceforge.net/api/axes_api.html