Creating vectors using Numpy

The data structure that we’ll need the most often is a vector and here are few examples of how we can generate  a vector using numpy package in Python.
First we’ll create a list of numbers and then using numpy array function transform the list into a numpy array or in our case vector.
b = [0, 0.5, 1, 1.5]
print "b_type = " + str(type(b))
print "b = " + str(b)
x = np.array(b)
print "x_type = " + str(type(x))
print "x = " + str(x)
After running this code in Spyder you’ll get the following result.
b_type = 
b = [0, 0.5, 1, 1.5]
x_type = 
x = [ 0.   0.5  1.   1.5]
Now we’ll show you how to use numpy Array range function to create a vector. Type the following code.
>>> x = N.arange(0, 2, 0.5)
>>> print x
[ 0.   0.5  1.   1.5]
Function aranage() is short for array range. In our case we’ve wanted to build an array (vector) from 0 to 2 with increment 0.5. This means that our vector has 4 elements that is 0, 0.5, 1., 1.5. Well the problem is that 2 is left out and the reason for that is that upper limit of an array is not included. It’s the same procedure when you’re creating lists.
Now we’ll create a null-vector with 4 elements. So type the code bellow.
>>> x = N.zeros(4)
>>> print x
[ 0.  0.  0.  0.]
Once array is established, we can set and retrieve individual values. For example:
>>> x = N.zeros(4)
>>> x[0] = 3.4
>>> x[2] = 4
>>> print x
[ 3.4  0.   4.   0. ]
>>> print(x[0])
3.4
>>> print(x[0:-1])
[ 3.4  0.   4. ]
Note that once we have a vector we can perform calculations on every element in the vector with a single statement:
>>> x = N.arange(0, 2, 0.5)
>>> print x
[ 0.   0.5  1.   1.5]
>>> print x+10
[ 10.   10.5  11.   11.5]
>>> print x**2
[ 0.    0.25  1.    2.25]
>>> print(N.sin(x))
[ 0.          0.47942554  0.84147098  0.99749499]

2 komentara: