arrays.txt
author Santosh G. Vattam <vattam.santosh@gmail.com>
Thu, 15 Apr 2010 15:58:46 +0530
changeset 72 7d4ed969a942
parent 70 c172d36d9a76
child 75 3a94917224e9
permissions -rw-r--r--
Minor edits.

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 are going to cover more details on using Arrays as matrices, such as, how to create them, how to initialize them, how to manipulate and use them for solving given problem.

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 equal to 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
i = identity(5)
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/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

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
Functions available for arrays

Thank you

----------------
We have seen 
    Welcome to the Tutorial on arrays. 

    As mentioned in [the previous tutorial] arrays are much faster and
    more efficient. In this tutorial we shall look at creating arrays,
    accessing elements and changing them. 

    ---

    Let's start with creating simple arrays. We've already seen how to
    convert lists to arrays. Inputting a new array is similar to that. 

    In []: 

    Type /a/, to see what it is. 

    In []: a
    
    We enter a multi-dimensional array this way -
    
    In []: c = array([[11,12,13],
                     [21,22,23],
                      [31,32,33]])

    To see what c is, we just type c in the prompt. 
		      
    In []: c

    To see the dimensions of the array c, we use c.shape
    In []: c.shape 

    Now let us look at some special methods of creating an
    array. There are various functions that allow us to create special
    arrays. 

    The first one we shall look at is, /arange/. /arange/ is similar to
    the range command, except that it returns an array and accepts
    float arguments. 
    
    In []: a = arange(10)
    
    In []: a
    This is the array we just created. 
    
    In []: a.shape
    Note that /a/ is one dimensional and has 10 elements, as expected. 

    We could also use a.shape to change the shape of the array a. 
    In []: a.shape = 2,5
    Note that the total size of new array must be unchanged. 

    We type a, to see what it looks like
    In []: a

    ones command can be used to get an array with all the entries as
    ones. We pass it the shape of the array that we require. 
    
    In []: 

    Look at b, by printing it out. 
    In []: b 

    To create an array with all entries as ones, with it's shape
    similar to an already existing array, we use the ones_like
    command.  
    In []: b = ones_like(a)

    zeros and zeros_like are similar commands that can give you arrays
    with all zeros. empty and empty_like give you empty arrays (arrays
    with no initialization done.)

    In []: b = zeros((3, 4))
    In []: b = zeros_like(a)

    The identity command can be used to obtain a square array with
    ones on the main diagonal. 
    
    In []: identity(3)

    To obtain a 2-D array, that is not necessarily square, eye command
    can be used. Look at the documentation of eye (using eye?) for
    more info. 

    ---
    
    Now that we have learnt how to create arrays, let's move on to
    accessing elements and changing them. 
    
    Let's work with the c, array which we had already created. 

    In []: c 

    Let's say we want to access the element 23 in c, we say

    In []: c[1][2]
    Note that this is similar to accessing an element inside a list of
    lists. Also, note that counting again starts from 0. 
    
    But arrays provide a more convenient way to access the elements. 
    In []: c[1, 2]
    
    Now, we can also change the element using a simple assignment. 
    In []: c[1, 2] = -23

    Let's look at accessing more than one elements at a time. We begin
    with accessing rows. 
    In []: c[1] gives us the second row. (counting starts from 0)

    To get a column, we use a syntax that is similar to the one used
    to access a single element. 
    In []: c[:,1], gives us the first column. 
    
    The colon specifies that we wish to obtain all elements in that
    dimension from the array.  

    So, we could use a more explicit way to access the second row of
    the array. 
    In []: c[1,:]
    
    The colon can be used to access specific portions of the array,
    similar to the way we do with lists. 
    In []: c[1,1:3]
    Observe that we get the second and third columns from the second
    row. As with lists, the number after the colon is excluded when
    slicing a portion of the array. 

    In []: c[1:3,1]
    Now, we get the second and third rows from the first column. 

    In []: c[1:3,1:3]
    We get the second and third rows and the second and third
    columns. 

    The numbers before and after the colons are optional. If the
    number before the colon is omitted, it is assumed to be zero by
    default. If the element after the colon is omitted, it is assumed
    to be until the end. 

    In []: c[1:, 1:]
    This is essentially similar to the previous example. We are using
    the default value i.e, the end, instead of specifying 3,
    explicitly. 

    In []: c[:2, :2]
    We have omitted specifying the zero before the colon, explicitly. 

    --- 
    
    You may have observed the similarity of the semi-colon notation to
    the notation used in lists. As expected, the semi-colon notation
    also provides a way to specify a jump. This {concept/idea} is
    termed as Striding. 

    To get every alternate row of c, starting from the first one, we say
    In []: c[::2,:]

    To get every alternate row of c, starting from the second one, we
    say 
    In []: c[1::2,:]


    In []: c[:,::2]
    In []: c[::2,::2]

    ---

    We come to the end of this tutorial on arrays. In this tutorial,
    you've learnt how to create arrays and access, change elements. 

    Thank you. 

Hello friends and welcome to the second tutorial in the series of spoken tutorials on Python for Scientific computing. 

In the previous tutorial we learnt about arrays and we told you that numpy arrays are faster and more efficient . In this tutorial we shall look at creating arrays, accessing elements and changing them. 


Let's start with creating simple arrays. We've already seen how to convert lists to arrays. Inputting a new array is similarto that. 

On your Ipython terminal type a = array open parenthesis and then open square brackets 5,8,10,13 close square brackets and close parenthesis . This create an array a . You can see what a is by typing a on the terminal .
Now we shall try to create a multi-dimensional array type in your ipython terminal
c= array open parenthesis , then open square brackets 11,12,13 close square bracket 'comma' start square bracket 21 , 22 ,23close square bracket 'comma' open 31,32,33 close square bracket another close square bracket which closes the first sqaure bracket and parenthesis which closes the first parenthesis . Now to see the dimensions of the array c we do c.shape . We can see that c is a 3 by 3 matrix .

There are other special methods of creating arrays as well we shall now look at them .
The first one is the command arange which is similar to range except that it returns an array.
We type on our Ipython interpreter a = arange(10). We see what a is now . Type a . As we can see This returns us an array of one dimension and has 10 elements .  
Ones can be use to get all entries as ones . We can pass it the shape of the array as required .
type b=ones open parenthesis , another open parenthesis , 3,4 , close second parenthesis and close first parenthesis . Look at b , by printing it out .
To create an array with all entries as ones, with it's shape similar to an already existing array, we use the ones_like
command.  type b= ones_like in parenthesis a .