arrays.txt
author Shantanu <shantanu@fossee.in>
Wed, 14 Apr 2010 16:40:58 +0530
changeset 56 86c862b3dbef
parent 55 1fe734b20950
child 61 38ef280b1408
permissions -rw-r--r--
First cut for arrays and matrices.

Hello and welcome to the tutorial on Matrices.
All matrices operations are done using arrays.
We have already seen in previous session that how arrays are better suited for particular mathematical operations. In this session we are going to cover more details on Arrays, how to create/initialize them, how to manipulate and use them for solving given problem.

First thing first, we start with creating a normal array by:
a (equal to)= array([5, 8, 10, 13])

and we have a as array. we can cross the content by
a

Here a is single dimension array, that is it has only one row. We can create 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

some other handy array initialization methods are also available to make life easier.
say we want to create a array of size 3x4 with all values initialized to be 1, we can use
b = ones((3, 4))
check value by
b
similarly, we already have a array, and we want to create one more array with same shape and initial values to be one, for that we will use
d = ones_like(c)
and d will be 3x3 array with all values 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(array) of given order
i = identity(3)
i
i = identity(5)
i

----------------
Now that we have covered creation of arrays, we will see how to access and change values of particular elements. 
We created one 3x3 matrix earlier, 
c

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

It is second row third column of c. Note that index values of arrays also start from 0.
Alternative and popular way of doing this 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]
will give us the entire second row.

The way by which we access one element of array, we use that itself to assign new value
c[1, 1] = -22
c

and same thing can be used for entire row
c[1] = 0
c
as we can see, second row all elements are now 0

Accessing a row is straight forward we skip column part
but to access whole column we have to use
c[:,2]
will return 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,:]
will result in rows starting from first(0) till second and all columns. Note here that 'end' in our case, '2' would 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]
will also give us first two columns
and c[:, 1:] will return last columns.

c[1:, :2]
returns first two columns of last two rows

Now we will look into one more powerful feature of arrays: 'striding'.
Striding allows us to jump or skip rows or columns by certain interval. We can specify the step size.
c[:,:] will give us entire array
we add one more ':' to row or column part to specify a step size.
c[:, ::2]
will give us first and third column. Since step size is two, it start with first column(blank before : means 0) and then we jump one column and then third(blank after : means end)
similarly 
c[::2,:] returns 2x3 array with first and third row

and c[::2, ::2] will give us 2x2 array with first and 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 imread to read images. We will use '(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 top left quarter by
imshow(a[:255,:255]) (half of 512 is 256)

But hat is not 'interesting' part of lena. Lets crop the image so that only her face is visible. for that we will need some rough estimates of pixels. 
imshow(a)
now move your mouse cursor over the image, it will give us x, y coordinates where ever we take our cursor. We can get rough estimate of lena's face now cropping to those boundaries is simple
imshow(a[200:400, 200:400])

Next we will try striding on this image. We will resize the image by skipping each alternate pixel. 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
sum() function returns sum of all the elements of a matrix.
sum(a)

lets 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]])

+ will take care of matrix additions
a + b

lets try multiplication now, 
a * b will return element wise product of two matrices.

To get matrix product of a and b we use
dot(a, b)

and to get inverse of matrix 

inv(a)

det(a) returns determinant of matrix a

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

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 will 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 will 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 will now look at them .
The first one is the command arange which is similar to range except that it returns an array.
We will type on our Ipython interpreter a = arange(10). We will 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 .