Python-Old-Version/C3/Arrays-Matrices/English

From Script | Spoken-Tutorial
Jump to: navigation, search

Hello friends and welcome to this tutorial on Matrices. In python all matrix operations are done using arrays. We have already seen in previous session that how arrays are better suited for certain mathematical operations. In this session we shall see how to perform efficient matrix operations using arrays. We shall see how to create them, how to initialize them, how to manipulate and use them to perform some basic image processing. 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 fire up Ipython,

ipython -pylab

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

a = array([5, 8, 10, 13])

let's check the value of a by typing

a

Here a is single dimension array, that is it has only one row. Let's now look at creating multi-dimensional arrays by

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

both c and a are arrays but with different dimensions or shape, we can check shape of arrays by using shape attribute of arrays.

a.shape
c.shape

A few other handy 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 'c' but with all elements as 1 we type:

d = ones_like(c)

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 identity 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,

c

to access the element 23 we type

c[1][2]

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

c[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 simply skip the column value

c[1]

gives us the entire second row. We can assign a new value to an element, the same way we accessed it. For eg.,

c[1, 1] = -22
c

In order to change an entire row we type:

c[1] = 0
c

as we can see, all elements of the second row are now 0. Accessing a row is straight forward we skip column part but the same cannot be done to access columns. In order to access the whole column we have to use ':'

c[:,2]

returns the third column. Here the ':' part mentioned for row value symbolises entire row. The c[1] we were using earlier can also be written as c[1,:] ':' actually takes two value. for any row or column we can mention start:end values, and rows or columns starting for 'start' till 'end' will be returned. Lets try some examples for better understanding

c[0:2,:]

results in rows starting from row zero(0) upto the second row and all columns. Note here that 'end', in this case, '2' will not be included in resulting array.

c[1:3,:] 

gives second and third row. Similarly we can try this on columns also:

c[:, 0:2] 

gives us first two column. This whole concept of accessing chunks of arrays is known as 'slicing'. There is one more interesting and handy feature of slicing. We saw earlier that how only ':' means entire row or column. It actually means if we don't specify start and end part of slice default is from zero to end. so

c[:, :2]

also gives us first two columns and c[:, 1:] returns all columns excluding the 0th column.

c[1:, :2]

returns first two columns of all rows excepting the 0th row. Now we shall look into one more powerful feature of arrays: 'striding'. Striding allows us to jump or skip, rows or columns by a certain interval. We can specify the step size.

c[:,:] 

gives us entire array. We add one more ':' to row or column part to specify a step size.

c[:, ::2]

gives us first and third column. Since step size is two, it starts with the first column(blank before : means 0) and then we jump one column and then third(blank after : means end) similarly

c[::2,:] 

returns a 2x3 array with the first and the third row and

c[::2, ::2] 

gives us a 2x2 array with the first and the third row and column. Lets us try to use these concepts of slicing and striding for doing some basic image manipulation pylab has a function named imread to read images. We shall use the '(in)famous' lena image for our experimentation. Its there on desktop.

a = imread('lena.png')

a is a numpy array with the 'RGB' values of each pixel

a.shape

its a 512x512x3 array. To view the image write

imshow(a)

lets try to crop the image to top left quarter. Since a is a normal array we can use slicing to get the top left quarter by

imshow(a[:255,:255]) 

(half of 512 is 256) Lena's hat is not of much interest for us. Let's crop the image so that only her face is visible. And to do that we'll need some rough estimates of pixels.

imshow(a)

now move your mouse pointer over the image, it gives us x, y coordinates of the mouse pointer's current location. We can get rough estimate of lena's face. We can 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 now the size of image is just 256x256 and still quality of image is not much compromised.


Till now we have covered initializing and accessing elements of arrays. Now we shall concentrate on functions available for arrays. We start this by creating 4x4 array by

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 the element wise product of two matrices. To get matrix product of 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. Now we shall create an array e

e = array([[3,2,4],[2,0,2],[4,2,3]])

and then to evaluate eigenvalues of array

eig(e)

it 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 and Functions available for arrays. Thank you.

Contributors and Content Editors

Chandrika