You are on page 1of 21

In [ ]: ## Numpy Practice

Vectors, Matrices

In [1]: import numpy as np


my_list = [1, 2, 3]

In [2]: arr = np.array(my_list)


print("Type/Class of this object: ", type(arr))
print("Here is the vector\n---------------\n",arr)

Type/Class of this object: <class 'numpy.ndarray'>


Here is the vector
---------------
[1 2 3]

In [3]: my_mat = [[1,2,3],[4,5,6],[7,8,9]]


mat = np.array(my_mat)
print("Type/Class of this object:",type(mat))
print("Here is the matrix\n----------\n",mat,"\n-----------")
print("Dimension of this matrix: ", mat.ndim,sep=' ')#ndim gives the dimensison
# sep adds seprator specif
print("Size of this matrix ",mat.size, sep = '----') #size gives the total number of elemen
print("Shape of this matrix: ", mat.shape, sep='+++++') #shape gives the number of elements
print("Data type of this matrix: ",mat.dtype,sep= '""""') # #dtype gives the data type con

Type/Class of this object: <class 'numpy.ndarray'>


Here is the matrix
----------
[[1 2 3]
[4 5 6]
[7 8 9]]
-----------
Dimension of this matrix: 2
Size of this matrix ----9
Shape of this matrix: +++++(3, 3)
Data type of this matrix: """"int32

In [4]: b = np.array([(1,5,2,3),(4,5,6)]) # made from tuples


print("We write b = np.array([(1.5,2,3), (4,5,6)])")
print("Matrix made from tuples, not lists\n---------------------------------------")
print(b)

We write b = np.array([(1.5,2,3), (4,5,6)])


Matrix made from tuples, not lists
---------------------------------------
[(1, 5, 2, 3) (4, 5, 6)]

'arange' and 'linspace'

In [5]: print("A series of numbers:", np.arange(5,16)) # A series of numbers from low to high

A series of numbers: [ 5 6 7 8 9 10 11 12 13 14 15]


In [6]: print("Numbers spaced spart by 2: ", np.arange(0,11,2)) # Numbers spaced apart by 2

Numbers spaced spart by 2: [ 0 2 4 6 8 10]

In [7]: print("Numbers spaced apart by a float: ", np.arange(0,12,2.5)) # Numbers spaced apart by 2

Numbers spaced apart by a float: [ 0. 2.5 5. 7.5 10. ]

In [8]: print("Every 5th number from 50 in reverse order\n", np.arange(50,-1,-5)) # -1 here is the

Every 5th number from 50 in reverse order


[50 45 40 35 30 25 20 15 10 5 0]

In [9]: print("21 linearly spaced numbers between 1 and 5\n---------------------------------------


print(np.linspace(1,5,21))

21 linearly spaced numbers between 1 and 5


--------------------------------------------
[1. 1.2 1.4 1.6 1.8 2. 2.2 2.4 2.6 2.8 3. 3.2 3.4 3.6 3.8 4. 4.2 4.4
4.6 4.8 5. ]

Zeroes, Ones, empty, and Identity matrix

In [10]: print("Vector of zeroes\n---------------------")


print(np.zeros(5))
print("Matrix of zeroes\n--------------------")
print(np.zeros((3,4))) # Notice Tuples

Vector of zeroes
---------------------
[0. 0. 0. 0. 0.]
Matrix of zeroes
--------------------
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]

In [11]: print("Vector of ones\n---------------------")


print(np.ones(5))
print("Matrix of ones\n---------------------")
print(np.ones((5,2))) # Note matrix dimension specified by Tuples

Vector of ones
---------------------
[1. 1. 1. 1. 1.]
Matrix of ones
---------------------
[[1. 1.]
[1. 1.]
[1. 1.]
[1. 1.]
[1. 1.]]
In [12]: print("Empty matrix\n-------------\n", np.empty((3,5)))

Empty matrix
-------------
[[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]

In [13]: mat1 = np.eye(4)


print("Identity matrix of dimension", mat1.shape)
print(mat1)

Identity matrix of dimension (4, 4)


[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]

Random number generation

In [14]: print("Random number generation (from Uniform distribution)")


print(np.random.rand(2,3)) # 2 by 3 matrix with random numbers ranging from 0 to 1, Note no

Random number generation (from Uniform distribution)


[[0.17340563 0.35152396 0.14131986]
[0.19871637 0.85194931 0.84837688]]

In [15]: print("Numbers from Normal distribution with zero mean and standard deviation 1 i.e. stand
print(np.random.randn(4,3))

Numbers from Normal distribution with zero mean and standard deviation 1 i.e. standard no
rmal
[[-0.8728734 0.74094813 -2.14250507]
[ 0.44377036 -0.77978949 -0.58962596]
[-0.31112299 -0.42895076 -0.81483648]
[ 0.21056997 1.71909533 0.31323054]]

In [16]: print("Random integer vector:",np.random.randint(1,100,10)) #randint (low, high, # of samp


print ("\nRandom integer matrix")
print(np.random.randint(1,100,(4,4))) ##randint (low, high, # of samples to be drawn in a
print("\n20 samples drawn from a dice throw:",np.random.randint(1,7,20)) # 20 samples drawn

Random integer vector: [96 79 34 77 77 3 77 28 37 6]

Random integer matrix


[[49 58 61 68]
[56 94 15 43]
[93 32 63 54]
[93 65 28 39]]

20 samples drawn from a dice throw: [5 3 4 4 2 6 4 2 1 3 3 1 6 4 4 5 3 2 4 3]

Reshaping, min, max, sort


In [17]: from numpy.random import randint as ri
a = ri(1,100,30)
b = a.reshape(2,3,5) # means 2, 3 X 5 matrices

b = a.reshape(3,2,5) # three 2 X 5 matrices

c= a.reshape(6,5)

print("Shape of a:", a.shape)


print("Shape of b:", b.shape)
print("Shape of c:", c.shape)
print("\na looks like\n",'-'*20,"\n",a,"\n",'-'*20)
print("\nb looks like\n",'-'*20,"\n",b,"\n",'-'*20)
print("\nc looks like\n",'-'*20,"\n",c,"\n",'-'*20)

Shape of a: (30,)
Shape of b: (3, 2, 5)
Shape of c: (6, 5)

a looks like
--------------------
[81 51 2 18 27 83 18 75 8 40 29 10 34 95 60 69 49 48 21 19 15 15 94 23
82 14 25 25 38 3]
--------------------

b looks like
--------------------
[[[81 51 2 18 27]
[83 18 75 8 40]]

[[29 10 34 95 60]
[69 49 48 21 19]]

[[15 15 94 23 82]
[14 25 25 38 3]]]
--------------------

c looks like
--------------------
[[81 51 2 18 27]
[83 18 75 8 40]
[29 10 34 95 60]
[69 49 48 21 19]
[15 15 94 23 82]
[14 25 25 38 3]]
--------------------
In [18]: A = ri(1,100,10) #Vector of random integers
print("\nVector of random integers\n",'-'*50,"\n",A)
print("\nHere is the sorted vector\n",'-'*50,"\n",np.sort(A, kind='mergesort'))

M = ri(1,100,25).reshape(5,5) # Matrix of random interegrs


print("\n5x5 Matrix of random integers\n",'-'*50,"\n",M)
print("\nHere is the sorted matrix along each row\n",'-'*50,"\n",np.sort(M, kind = 'mergeso
print("\nHere is the sorted matrix along each column\n",'-'*50,"\n",np.sort(M, axis=0, kind

Vector of random integers


--------------------------------------------------
[84 32 48 4 27 31 72 23 32 34]

Here is the sorted vector


--------------------------------------------------
[ 4 23 27 31 32 32 34 48 72 84]

5x5 Matrix of random integers


--------------------------------------------------
[[53 83 91 82 30]
[74 7 80 68 76]
[41 71 25 65 83]
[29 17 90 82 57]
[58 11 65 4 89]]

Here is the sorted matrix along each row


--------------------------------------------------
[[30 53 82 83 91]
[ 7 68 74 76 80]
[25 41 65 71 83]
[17 29 57 82 90]
[ 4 11 58 65 89]]

Here is the sorted matrix along each column


--------------------------------------------------
[[29 7 25 4 30]
[41 11 65 65 57]
[53 17 80 68 76]
[58 71 90 82 83]
[74 83 91 82 89]]

In [19]: print("Max of a:", a.max())


print("Max of b:", b.max())
print(a)
print("Max of a location:", a.argmax()) # Index of maximum value along the axis
print("max of b location:", b.argmax())
print("Max of c location:", c.argmax())

Max of a: 95
Max of b: 95
[81 51 2 18 27 83 18 75 8 40 29 10 34 95 60 69 49 48 21 19 15 15 94 23
82 14 25 25 38 3]
Max of a location: 13
max of b location: 13
Max of c location: 13

Indexing and slicing


In [20]: arr = np.arange(0,11)
print("Array:",arr)
print("Element at 7th index is:", arr[7])
print("Elements from 3rd to 5th index are:", arr[3:6])
print("Elements up to 4th index are:", arr[:4])
print("Elements from last backwards are:", arr[-1::-1]) # Here -1 is step
print("3 Elements from last backwards are:", arr[-1:-6:-2]) # -2 is step

Array: [ 0 1 2 3 4 5 6 7 8 9 10]
Element at 7th index is: 7
Elements from 3rd to 5th index are: [3 4 5]
Elements up to 4th index are: [0 1 2 3]
Elements from last backwards are: [10 9 8 7 6 5 4 3 2 1 0]
3 Elements from last backwards are: [10 8 6]

In [21]: arr = np.arange(0,21,2)


print("New Array:",arr)
print("Elements at 2nd, 4th, and 9th index are:",arr[[2,4,9]]) # passing indexes as list

New Array: [ 0 2 4 6 8 10 12 14 16 18 20]


Elements at 2nd, 4th, and 9th index are: [ 4 8 18]
In [22]: mat = np.array(ri(10,100,15)).reshape(3,5)
print("Matrix of random 2-digit numbers\n--------------------------------\n",mat)

print("\nDouble bracket indexing\n------------------------") # using 2 square brackets


print("Element in row index 1 and column index 2:", mat[1][2])

print("\nSingle bracket with comma indexing\n----------------------------------")


print("Element in row index 1 and column index 2:", mat[1,2]) # using single square bracke
print("\nRow or column extract\n----------------------")

print("Entire row at index 2:", mat[2])


print("Entire column at index 3:", mat[:,3])

print("\nSubsetting sub-matrices\n--------------------------")
print("Matrix with row indices 1 and 2 and column indices 3 and 4\n", mat[1:3,3:5])
print("Matrix with row indices 0 and 1 and column indices 1 and 3\n", mat[0:2,[1,3]])

Matrix of random 2-digit numbers


--------------------------------
[[77 10 48 94 72]
[17 77 86 60 66]
[50 34 85 28 19]]

Double bracket indexing


------------------------
Element in row index 1 and column index 2: 86

Single bracket with comma indexing


----------------------------------
Element in row index 1 and column index 2: 86

Row or column extract


----------------------
Entire row at index 2: [50 34 85 28 19]
Entire column at index 3: [94 60 28]

Subsetting sub-matrices
--------------------------
Matrix with row indices 1 and 2 and column indices 3 and 4
[[60 66]
[28 19]]
Matrix with row indices 0 and 1 and column indices 1 and 3
[[10 94]
[77 60]]

Conditional subsetting

In [23]: mat = np.array(ri(10,100,15)).reshape(3,5)


print("Matrix of random 2-digit numbers\n--------------------------------\n",mat)
print ("\nElements greater than 50\n", mat[mat>50])

Matrix of random 2-digit numbers


--------------------------------
[[47 54 69 58 75]
[97 27 28 74 38]
[79 74 77 98 15]]

Elements greater than 50


[54 69 58 75 97 74 79 74 77 98]
Slicing keeps the original reference, be aware of mutating the original
array
In [37]: mat = np.array([[11,12,13],[21,22,23],[31,32,33]])
print("Original matrix")
print(mat)

mat_slice = mat[:2,:2]
print ("\nSliced matrix")
print(mat_slice)

print ("\nChange the sliced matrix")


mat_slice[0,0] = 100 # Changed the (0,0) element
print(mat_slice)

print("\nBut the original matrix? WHOA! It got changed too!") # Sliced array points to or
print(mat)

# Little different way to create a copy of the slixed matrix


print ("\nDoing it again little differently now...\n")
mat = np.array([[11,12,13],[21,22,23],[31,32,33]])
print("Original matrix")
print(mat)

mat_slice = np.array(mat[:2,:2]) # Notice the np.array command to create a new array not ju
print ("\nSliced matrix")
print(mat_slice)
print ("\nChange the sliced matrix")
mat_slice[0,0]= 100
print(mat_slice)

print("\nBut the original matrix? NO CHANGE this time:)") # using nparray created to pointe
print(mat)

Original matrix
[[11 12 13]
[21 22 23]
[31 32 33]]

Sliced matrix
[[11 12]
[21 22]]

Change the sliced matrix


[[100 12]
[ 21 22]]

But the original matrix? WHOA! It got changed too!


[[100 12 13]
[ 21 22 23]
[ 31 32 33]]

Doing it again little differently now...

Original matrix
[[11 12 13]
[21 22 23]
[31 32 33]]

Sliced matrix
[[11 12]
[21 22]]

Change the sliced matrix


[[100 12]
[ 21 22]]

But the original matrix? NO CHANGE this time:)


[[11 12 13]
[21 22 23]
[31 32 33]]

Array operations (array-array, array-scalar, universal functions)

In [41]: mat1 = np.array(ri(1,10,9)).reshape(3,3)


mat2 = np.array(ri(1,10,9)).reshape(3,3)
print("\n1st Matrix of random single-digit numbers\n--------------------------------------
print("\n2nd Matrix of random single-digit numbers\n--------------------------------------

print("\nAddition\n------------------\n", mat1+mat2)
print("\nMultiplication\n------------------\n", mat1*mat2)
print("\nDivision\n------------------\n", mat1/mat2)
print("\nLineaer combination: 3*A - 2*B\n-----------------------------\n", 3*mat1-2*mat2)

1st Matrix of random single-digit numbers


----------------------------------------
[[8 5 2]
[3 3 5]
[2 3 8]]

2nd Matrix of random single-digit numbers


----------------------------------------
[[7 3 7]
[9 3 3]
[2 9 6]]

Addition
------------------
[[15 8 9]
[12 6 8]
[ 4 12 14]]

Multiplication
------------------
[[56 15 14]
[27 9 15]
[ 4 27 48]]

Division
------------------
[[1.14285714 1.66666667 0.28571429]
[0.33333333 1. 1.66666667]
[1. 0.33333333 1.33333333]]

Lineaer combination: 3*A - 2*B


-----------------------------
[[10 9 -8]
[-9 3 9]
[ 2 -9 12]]

Broadcasting (super cool feature)


NumPy operations are usually done on pairs of arrays on an element-by-element basis. In the simplest case,
the two arrays must have exactly the same shape.

NumPy’s broadcasting rule relaxes this constraint when the arrays’ shapes meet certain constraints. When
operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions,
and works its way forward. Two dimensions are compatible when

they are equal, or one of them is 1 If these conditions are not met, a ValueError: frames are not aligned
exception is thrown, indicating that the arrays have incompatible shapes. The size of the resulting array is the
maximum size along each dimension of the input arrays

In [43]: start = np.zeros((4,3))


print(start)

[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]

In [44]: # create a rank 1 ndarray with 3 values


add_rows = np.array([1,0,2])
print(add_rows)

[1 0 2]

In [46]: y = start + add_rows # add to each row of 'start' using broadcasting


print(y)

[[1. 0. 2.]
[1. 0. 2.]
[1. 0. 2.]
[1. 0. 2.]]

In [48]: # create an ndarray which is 4 x 1 to broadcast across columns


add_cols = np.array([[0,1,2,3]])
add_cols = add_cols.T # T is for transpose
print(add_cols)

[[0]
[1]
[2]
[3]]

In [49]: # add to each column of 'start' using broadcasting


y = start + add_cols # This add 'add_cols' to every column of 'start'
print(y)

[[0. 0. 0.]
[1. 1. 1.]
[2. 2. 2.]
[3. 3. 3.]]
In [51]: # this will just broadcast in both dimensions
add_scalar = np.array([100])
print(add_scalar)
print(start + add_scalar)

[100]
[[100. 100. 100.]
[100. 100. 100.]
[100. 100. 100.]
[100. 100. 100.]]

NumPy mathematical functions on array


In [63]: mat1 = np.array(ri(1,10,9)).reshape(3,3)
mat2 = np.array(ri(1,10,9)).reshape(3,3)
print("\n1st Matrix of random single-digit numbers\n--------------------------------------
print("\n2nd Matrix of random single-digit numbers\n--------------------------------------

print("\nSq-root of 1st matrix using np\n------------------\n", np.sqrt(mat1))


print("\nExponential power of 1st matrix using np\n",'-'*50,"\n", np.exp(mat1))
print("\n10-base logarithm on 1st matrix using np\n",'-'*50,"\n", np.log10(mat1))
print("\nModulo reminder using np\n",'-'*50,"\n", np.fmod(mat1,mat2)) # remaineder of mat1/

print("\nCombination of functions by shwoing exponetial decay of a sine wave\n",'-'*70)


A = np.linspace(0,12*np.pi,1001)
print(A.size)

import matplotlib.pyplot as plt


plt.scatter(x=A,y=100*np.exp(-A/10)*(np.sin(A)))
plt.title("Exponential decay of sine wave: exp(-x)*sin(x)")
plt.show()

1st Matrix of random single-digit numbers


----------------------------------------
[[6 3 6]
[5 9 3]
[8 9 1]]

2nd Matrix of random single-digit numbers


----------------------------------------
[[7 3 9]
[2 9 6]
[4 7 7]]

Sq-root of 1st matrix using np


------------------
[[2.44948974 1.73205081 2.44948974]
[2.23606798 3. 1.73205081]
[2.82842712 3. 1. ]]

Exponential power of 1st matrix using np


--------------------------------------------------
[[4.03428793e+02 2.00855369e+01 4.03428793e+02]
[1.48413159e+02 8.10308393e+03 2.00855369e+01]
[2.98095799e+03 8.10308393e+03 2.71828183e+00]]

10-base logarithm on 1st matrix using np


--------------------------------------------------
[[0.77815125 0.47712125 0.77815125]
[0.69897 0.95424251 0.47712125]
[0.90308999 0.95424251 0. ]]

Modulo reminder using np


--------------------------------------------------
[[6 0 6]
[1 0 3]
[0 2 1]]

Combination of functions by shwoing exponetial decay of a sine wave


----------------------------------------------------------------------
1001
NumPy basic statistics on array
In [68]: mat1 = np.array(ri(1,10,9)).reshape(3,3)
mat2 = np.array(ri(1,10,9)).reshape(3,3)
print("\n1st Matrix of random single-digit numbers\n","-"*50,"\n",mat1)
print("\n2nd Matrix of random single-digit numbers\n","-"*50,"\n",mat2)

print("\nSum of all numbers in 1st matrix\n","-"*50,"\n",np.sum(mat1))


print("\nSum of all numbers in columns of 1st matrix\n","-"*50,"\n",np.sum(mat1, axis=0))
print("\nSum of all numbers in rows of 1st matrix\n","-"*50,"\n",np.sum(mat1,axis=1))
print("\nProduct of all numbers in rows of 1st matrix\n","-"*50,"\n",np.prod(mat1,axis=1))
print("\nProduct of all numbers in columns of 2nd matrix\n","-"*50,"\n",np.prod(mat2,axis=0
print("\nMean of all numbers in 1st matrix\n","-"*50,"\n",np.mean(mat1))
print("\nStandard deviation of all numbers in 1st matrix\n","-"*50,"\n",np.std(mat1))

mat1 = np.array(ri(1,100,9)).reshape(3,3)
print("\nModified matrix of random numbers from 1 to 99\n","-"*50,"\n",mat1)
print("\nStandard deviation of all numbers in the modified matrix, a larger number\n","-"*
print("\nVariance of all numbers in the modified matrix, a larger number\n","-"*80,"\n",np
print("\nMedian of all numbers in the modified matrix\n","-"*60,"\n",np.median(mat1))

mat2 = np.array(ri(1,100,50)).reshape(10,5)
print("\nModified matrix of 50 random numbers from 1 to 99\n","-"*50,"\n",mat2)
print("\nStandard deviation along the columns in the modified matrix\n","-"*60,"\n",np.std

mat1 = np.array(ri(1,100,20)).reshape(4,5)
print("\nModified matrix of random numbers from 1 to 49\n","-"*50,"\n",mat1)
print("\nFlattened and sorted matrix (as vector)\n","-"*50,"\n",np.sort(mat1.reshape(1,20)
print("\n50th percentile of all numbers in the modified matrix\n","-"*60,"\n",np.percentile
print("\n90th percentile of all numbers in the modified matrix\n","-"*60,"\n",np.percentile

1st Matrix of random single-digit numbers


--------------------------------------------------
[[3 9 1]
[7 4 2]
[8 6 4]]

2nd Matrix of random single-digit numbers


--------------------------------------------------
[[5 1 9]
[2 1 4]
[6 9 6]]

Sum of all numbers in 1st matrix


--------------------------------------------------
44

Sum of all numbers in columns of 1st matrix


--------------------------------------------------
[18 19 7]

Sum of all numbers in rows of 1st matrix


--------------------------------------------------
[13 13 18]

Product of all numbers in rows of 1st matrix


--------------------------------------------------
[ 27 56 192]

Product of all numbers in columns of 2nd matrix


--------------------------------------------------
[ 60 9 216]
Mean of all numbers in 1st matrix
--------------------------------------------------
4.888888888888889

Standard deviation of all numbers in 1st matrix


--------------------------------------------------
2.601044424604361

Modified matrix of random numbers from 1 to 99


--------------------------------------------------
[[17 80 16]
[17 52 4]
[74 48 60]]

Standard deviation of all numbers in the modified matrix, a larger number


--------------------------------------------------------------------------------
26.42996802640032

Variance of all numbers in the modified matrix, a larger number


--------------------------------------------------------------------------------
698.5432098765432

Median of all numbers in the modified matrix


------------------------------------------------------------
48.0

Modified matrix of 50 random numbers from 1 to 99


--------------------------------------------------
[[24 4 51 89 90]
[83 33 43 59 89]
[92 16 93 93 39]
[36 24 75 20 18]
[40 43 27 12 85]
[97 19 61 20 78]
[89 74 72 58 87]
[ 4 11 49 21 12]
[24 24 19 44 50]
[76 68 57 62 48]]

Standard deviation along the columns in the modified matrix


------------------------------------------------------------
[32.55840905 22.26746506 21.0905192 27.8057548 28.58391156]

Modified matrix of random numbers from 1 to 49


--------------------------------------------------
[[93 18 90 47 58]
[40 48 82 63 58]
[67 47 56 88 66]
[38 85 38 34 5]]

Flattened and sorted matrix (as vector)


--------------------------------------------------
[[ 5 18 34 38 38 40 47 47 48 56 58 58 63 66 67 82 85 88 90 93]]

50th percentile of all numbers in the modified matrix


------------------------------------------------------------
57.0

90th percentile of all numbers in the modified matrix


------------------------------------------------------------
88.2
Correlation and covariance

In [79]: A = ri(1,5,20) # 20 random integeres from a small range (1-10)


B = 2*A*np.random.randn(20) # B is twice that of A plus some random noise
print("\nB is twice that of A plus some random noise")
print(A)
print(B)

plt.scatter(A,B) # Scatter plot of B


plt.title("Scatter plot of A vs. B, expect a small positive correlation")
plt.show()

print(np.corrcoef(A,B)) # Correleation coefficient matrix between A and B

B is twice that of A plus some random noise


[2 4 4 4 4 4 4 1 2 4 3 1 3 2 1 3 1 3 4 3]
[ 6.68895858 7.91340658 2.54709034 -7.79109526 -9.87031056
-13.02458743 -4.90290905 -1.53629807 -1.12495803 8.56706308
7.09388149 -3.70727926 -10.86311383 -5.94280036 -0.48607006
-1.28211144 4.41311902 4.82317432 -7.22905605 -5.17518114]

[[ 1. -0.17056766]
[-0.17056766 1. ]]
In [80]: A = ri(1,50,20) # 20 random integeres from a larger range (1-50)
B = 100-2*A+10*np.random.randn(20) # B is 100 minus twice that of A plus some random noise
print("\nB is 100 minus twice that of A plus some random noise")
plt.scatter(A,B) # Scatter plot of B
plt.title("Scatter plot of A vs. B, expect a large negative correlation")
plt.show()
print("")
print(np.corrcoef(A,B)) # Correleation coefficient matrix between A and B

B is 100 minus twice that of A plus some random noise

[[ 1. -0.94690455]
[-0.94690455 1. ]]

Linear Algebra Operations

Dot/Inner/Outer products
In [83]: A = np.arange(1,10).reshape(3,3)
B = ri(1,10,9).reshape(3,3)
print("\n1st Matrix of 1-9 single-digit numbers (A)\n","-"*50,"\n",A)
print("\n2nd Matrix of random single-digit numbers (B)\n","-"*50,"\n",B)

print("\nDot product of A and B (for 2D arrays it is equivalent to matrix multiplication)

1st Matrix of 1-9 single-digit numbers (A)


--------------------------------------------------
[[1 2 3]
[4 5 6]
[7 8 9]]

2nd Matrix of random single-digit numbers (B)


--------------------------------------------------
[[9 7 8]
[4 6 8]
[9 1 2]]

Dot product of A and B (for 2D arrays it is equivalent to matrix multiplication)


--------------------------------------------------------------------------------
[[ 44 22 30]
[110 64 84]
[176 106 138]]

In [89]: A = np.arange(1,6)
B = ri(1,10,5)
print("\n1st Vector of 1-5 numbers (A)\n","-"*50,"\n",A)
print("\n2nd Vector of 5 random single-digit numbers (B)\n","-"*50,"\n",B)
print("\nInner product of vectors A and B \n","-"*50,"\n",np.inner(A,B)) # Sum of product o
print("\nOuter product of vectors A and B \n","-"*50,"\n",np.outer(A,B)) # Normail matrix m

1st Vector of 1-5 numbers (A)


--------------------------------------------------
[1 2 3 4 5]

2nd Vector of 5 random single-digit numbers (B)


--------------------------------------------------
[2 3 1 9 1]

Inner product of vectors A and B


--------------------------------------------------
52

Outer product of vectors A and B


--------------------------------------------------
[[ 2 3 1 9 1]
[ 4 6 2 18 2]
[ 6 9 3 27 3]
[ 8 12 4 36 4]
[10 15 5 45 5]]

Transpose
In [92]: A = ri(1,10,9).reshape(3,3)
print("\n3x3 Matrix of random single-digit numbers\n","-"*50,"\n",A)
print("\nMatrix transpose\n","-"*50,"\n",np.transpose(A))

B = ri(1,10,6).reshape(3,2)
print("\n3x2 Matrix of random single-digit numbers\n","-"*50,"\n",B)
print("\n2x3 Matrix transpose\n","-"*50,"\n",np.transpose(B))
print("\nMatrix multiplication of B and B-transpose\n","-"*50,"\n",np.dot(B, np.transpose(

3x3 Matrix of random single-digit numbers


--------------------------------------------------
[[6 3 2]
[7 1 5]
[5 2 7]]

Matrix transpose
--------------------------------------------------
[[6 7 5]
[3 1 2]
[2 5 7]]

3x2 Matrix of random single-digit numbers


--------------------------------------------------
[[2 8]
[1 8]
[2 4]]

2x3 Matrix transpose


--------------------------------------------------
[[2 1 2]
[8 8 4]]

Matrix multiplication of B and B-transpose


--------------------------------------------------
[[68 66 36]
[66 65 34]
[36 34 20]]

Trace
In [99]: A = ri(1,10,16).reshape(4,4)
print("\n4x4 Matrix of random single-digit numbers\n","-"*50,"\n",A)
print("\nMatrix trace\n","-"*50,"\n",np.trace(A)) # Sum of main diagonal elements
print("\nMatrix trace with ofset +1 (upper triangle)\n","-"*50,"\n",np.trace(A,offset=1)) #
print("\nMatrix trace with ofset +1 (upper triangle)\n","-"*50,"\n",np.trace(A,offset=2)) #
print("\nMatrix trace with ofset +1 (upper triangle)\n","-"*50,"\n",np.trace(A,offset=3))#
print("\nMatrix trace with ofset +1 (upper triangle)\n","-"*50,"\n",np.trace(A,offset=-1))

4x4 Matrix of random single-digit numbers


--------------------------------------------------
[[6 4 8 7]
[8 8 1 2]
[9 3 9 9]
[8 6 7 4]]

Matrix trace
--------------------------------------------------
27

Matrix trace with ofset +1 (upper triangle)


--------------------------------------------------
14

Matrix trace with ofset +1 (upper triangle)


--------------------------------------------------
10

Matrix trace with ofset +1 (upper triangle)


--------------------------------------------------
7

Matrix trace with ofset +1 (upper triangle)


--------------------------------------------------
18

In [ ]:

You might also like