arrays.txt
author asokan <asokan@fossee.in>
Tue, 18 May 2010 15:27:02 +0530
changeset 125 27ddf1255daa
parent 75 3a94917224e9
permissions -rw-r--r--
changes to array.txt

Hello friends and welcome to this tutorial on Matrices.

In python all matrix operations are done using arrays.

We saw in the previous session that arrays are better suited for mathematical operations. We saw this in the context of simple statistical functions such as mean.

In this session we shall see how to perform efficient matrix operations using arrays. We will create arrays, initialize them, manipulate them and perform simple image processing using them. For this tutorial we shall need the lena.png image. Hope you have the image with you. 

Let's now start off. As you can see our lena image is on the desktop, so first let's navigate to the desktop by cd Desktop.

Let's now start Ipython, using the command python -pylab

First things first, let's start by creating a normal array. 

Type:
p equal to array([5, 8, 10, 13])

let's check the value of a by typing
p
Note how python displays an array, compared to a list.

Here p is single dimension array, that is it has only one row. Let us now create a multi-dimensional array.

Type:

q = array([[11,12,13], [21,22,23], [31,32,33]])

both p and q are arrays but with different dimensions or shape
we can check shape of arrays by using shape attribute of arrays.
p.shape
q.shape

A few array initialization methods are also available to make life easier;
say we want to create an array of size 3x4 with all the elements initialized to 1, we use
b = ones((3, 4))
and b is
b
similarly, suppose we already have an array, and we want to create another array with the same shape but with initial values equal to one, for eg, to get an array similar in shape to the array 'q' but with all elements as 1 we type:
d = ones_like(q)
and d is a 3x3 array with all values equal to 1

Similarly there are functions like zeros and zeros_like which initialize array with all values being 0. One more useful function available is 'identity', it create unit matrix of given order
i = identity(3)
i

Note that identity takes just one argument since identity matrix is always a square matrix.

----------------
Now that we have covered creation of arrays, we shall see how to access and change values of particular elements. 
Remember we created a 3x3 matrix earlier, 
q

to access the element 23 we type
q[1][2]

It is at the second row of the third column of the matrix/array q. Note that index values of arrays also start from 0.
Alternatively, the more popular way of doing the same is
q[1, 2]

here ',' is used as separator for row and column value. Similarly any value from the array can be accessed.

to access particular row completely we specify the row value alone: 
q[1]
This gives us the entire second row. 

We can assign a new value to an element, the same way we accessed it. For eg., 
q[1, 1] = -22
q

One of the most powerful aspects of a high-level language like python is the way it supports matrix operations. We can use them like we do it maths rather than think of them as elements like a programmer.

For example to change a whole row, we type:
q[1] = 0
q
as we can see, all elements of the second row are now 0

In order to access a column, we need to syntactically indicate that the number given is the column index rather than the row index. In other words we need a placeholder for the row position. We cannot use space. That is we cannot say q[, 1] as that would be a syntax error ( q[m, n] being the method to access an _element_).

We have to say all rows and a column(s) by extending the slice notation seen earlier.
q[:,2]
returns the third column.
Here the ':' part specifies the row numbers of the slice; as we have seen before by leaving the from and to parts of the slice empty we effectively say ALL. Thus q[:, n] stands for a matrix which is the submatrix obtained by taking all rows and  column n+1.

The row reference q[1] can also be written as q[1,:]

As we have seen ':' takes two values namely start and end. As before rows or columns starting from 'start' till 'end' --excluding end-- will be returned. Lets try some examples:
q [0:2,:]
results in a matrix which is rows 0 and 1 and all columns. Note here that 'end', in this case, '2' will not be included in resulting matrix.

Similarly q[1:3,:] 
gives second and third rows.

q[:, 0:2] gives us first two columns

This manner of accessing chunks of arrays is also known as 'slicing'. Since the idea is the same as slicing for lists the name is also the same.

As noted the default values for slices carry over.
Thus
q[:, :2]
gives us the first two columns

q[:, 1:] 
returns all columns excluding the 0th column.

q[1:, :2]
returns first two columns of all rows excepting the 0th row.

When slicing lists we saw the idea of striding. Recall that if L is a list,
L[start : stop : step],
produces a new list whose first element is L[start] and has all elements whose index is start + n * step; stop signals the last index _before_ which we should stop.

Matrices also support striding--that is skip, rows or columns by a certain interval. 
We add one more ':' to row or column part to specify a step size.
Let us type 
q[:, ::2]
and see what is shown.
The first colon specifies that we pick all rows, the comma signals that we start specifying columns. The empty places indicate defaults. That is start from the 0th and go to the end. The presence of step--in this case 2--tells us that we will select alternate columns. Thus we q[:, ::2] extracts all rows and alternate columns starting with 0th column.

q[::2,:]
returns a 2x3 matrix with the first and the third row.

q[::2, ::2] 
gives us a 2x2 array with the first and the third rows and first and third columns. 

Lets us use slicing and striding for doing some basic image manipulation

pylab has a function named imread to read images. We shall use lena.png image for our experimentation. Its there on desktop. 

a = imread('lena.png')
Now a is an array with the RGB and Alpha channel values of each pixel
a.shape
tells us that 
it is an 512x512x4 array.

to view the image write
imshow(a)

lets try to crop the image to top left quarter. Since a is an array we can use slicing to get the top left quarter by
imshow(a[:256,:256]) (half of 512 is 256)

Let's crop the image so that only her face is visible. And to do that we'll need some rough estimates of the coordinates of the face.  
imshow(a)
now move your mouse pointer over the image, it gives us x, y coordinates of the mouse pointer's current location. With this we can get rough estimate of lena's face. We observe that Lena's face begins from somewhere around 200, 200 and ends at 400, 400. Now cropping to these boundaries is simple
imshow(a[200:400, 200:400])

Next we shall try striding on this image. We shall resize the image by skipping alternate pixels. We have already seen how to skip alternate elements so,
imshow(a[::2, ::2])
note that the size of image is just 256x256. 
------------------

Till now we have covered initializing and accessing elements of arrays. Now we shall look at other manipulations for arrays. We start by creating a 4x4 array 

a = array([[ 1, 1, 2, -1],[ 2, 5, -1, -9], [ 2, 1, -1, 3], [ 1, -3, 2, 7]])
a

To get transpose of this matrix write
a.T

The sum() function returns sum of all the elements of a matrix.
sum(a)

let's create one more array for checking more operations
b = array([[3,2,-1,5], [2,-2,4,9], [-1,0.5,-1,-7], [9,-5,7,3]])

+ takes care of matrix additions
a + b

lets try multiplication now, 
a * b returns a new matrix whose elements are products of corresponding elements. THIS IS NOT matrix multiplication.

To get the usual product of matrices a and b we use
dot(a, b)

To get the inverse of a matrix we use,

inv(a)

det(a) returns determinant of matrix a

we shall create an matrix e
e = array([[3,2,4],[2,0,2],[4,2,3]])
and then to evaluate eigenvalues of the same. 
eig(e)
returns both eigen values and eigen vector of given matrix
to get only eigen values use
eigvals(e)

This brings us to end of this session. We have covered Matrices
Initialization
Slicing
Striding
A bit of image processing
Functions available for arrays

Thank you