numpy-basics



In [1]:
import numpy as np
import matplotlib.pyplot as plt

Array initialization


In [2]:
ar1 = [1,2,3,4] # from lists
ar1 = np.array(ar1)
ar1


Out[2]:
array([1, 2, 3, 4])

In [4]:
# from matlab style syntax
ar2 = np.mat('1,2,3;4,5,6')
ar2


Out[4]:
matrix([[1, 2, 3],
        [4, 5, 6]])

Automatic map operations


In [5]:
squares = np.array([4,9,16,25,36,49])
np.sqrt(squares)


Out[5]:
array([2., 3., 4., 5., 6., 7.])

In [6]:
np.min(squares)


Out[6]:
4

Element wise operations

solve $f(x) = 3x^{2} + 2x -6$ for the range -2:0.1:2


In [45]:
x = np.arange(start=-2.0, stop=2.0, step=0.1)
x


Out[45]:
array([-2.00000000e+00, -1.90000000e+00, -1.80000000e+00, -1.70000000e+00,
       -1.60000000e+00, -1.50000000e+00, -1.40000000e+00, -1.30000000e+00,
       -1.20000000e+00, -1.10000000e+00, -1.00000000e+00, -9.00000000e-01,
       -8.00000000e-01, -7.00000000e-01, -6.00000000e-01, -5.00000000e-01,
       -4.00000000e-01, -3.00000000e-01, -2.00000000e-01, -1.00000000e-01,
        1.77635684e-15,  1.00000000e-01,  2.00000000e-01,  3.00000000e-01,
        4.00000000e-01,  5.00000000e-01,  6.00000000e-01,  7.00000000e-01,
        8.00000000e-01,  9.00000000e-01,  1.00000000e+00,  1.10000000e+00,
        1.20000000e+00,  1.30000000e+00,  1.40000000e+00,  1.50000000e+00,
        1.60000000e+00,  1.70000000e+00,  1.80000000e+00,  1.90000000e+00])

In [51]:
a=np.array([1,2,3])
a*a # element wise


Out[51]:
array([1, 4, 9])

In [52]:
np.dot(a,a) # matrix multiplication. It automatically changed second a to a col vector


Out[52]:
14

In [54]:
np.cross(a,a)


Out[54]:
array([0, 0, 0])

In [55]:
# thus, y
y = 3*x*x + 2*x -6
y


Out[55]:
array([ 2.  ,  1.03,  0.12, -0.73, -1.52, -2.25, -2.92, -3.53, -4.08,
       -4.57, -5.  , -5.37, -5.68, -5.93, -6.12, -6.25, -6.32, -6.33,
       -6.28, -6.17, -6.  , -5.77, -5.48, -5.13, -4.72, -4.25, -3.72,
       -3.13, -2.48, -1.77, -1.  , -0.17,  0.72,  1.67,  2.68,  3.75,
        4.88,  6.07,  7.32,  8.63])

In [58]:
plt.plot(x,y)
plt.title('$f(x) = 3x^{2} + 2x -6$')
plt.xlabel('x')
plt.ylabel('y');


Range functions


In [7]:
np.arange(start=0, stop=21, step=2)


Out[7]:
array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20])

In [9]:
v1 = np.linspace(start=1,stop=10, num=7)
v1


Out[9]:
array([ 1. ,  2.5,  4. ,  5.5,  7. ,  8.5, 10. ])

In [10]:
v1 > 4


Out[10]:
array([False, False, False,  True,  True,  True,  True])

In [41]:
v1[v1>4]


Out[41]:
array([ 5.5,  7. ,  8.5, 10. ])

In [40]:
v1[(v1>4) & (v1<9)]


Out[40]:
array([5.5, 7. , 8.5])