In [2]:
my_list = [1,2,3]
import numpy as np
arr = np.array(my_list)
print("Type/Class of this object:",type(arr))
print("Here is the vector\n--------------------\n",arr)
In [4]:
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, 2 for a matrix, 1 for a vector
print("Size of this matrix: ", mat.size,sep='') #size gives the total number of elements
print("Shape of this matrix: ", mat.shape,sep='') #shape gives the number of elements along each axes (dimension)
print("Data type of this matrix: ", mat.dtype,sep='') #dtype gives the data type contained in the array
my_mat = [[1.1,2,3],[4,5.2,6],[7,8.3,9]]
mat = np.array(my_mat)
print("Data type of the modified matrix: ", mat.dtype,sep='') #dtype gives the data type contained in the array
print("\n\nEven tuples can be converted to ndarrays...")
b = np.array([(1.5,2,3), (4,5,6)])
print("We write b = np.array([(1.5,2,3), (4,5,6)])")
print("Matrix made from tuples, not lists\n---------------------------------------")
print(b)
In [66]:
print("A series of numbers:",np.arange(5,16)) # A series of numbers from low to high
In [63]:
print("Numbers spaced apart by 2:",np.arange(0,11,2)) # Numbers spaced apart by 2
In [97]:
print("Numbers spaced apart by float:",np.arange(0,11,2.5)) # Numbers spaced apart by 2.5
In [71]:
print("Every 5th number from 50 in reverse order\n",np.arange(50,-1,-5))
In [73]:
print("21 linearly spaced numbers between 1 and 5\n--------------------------------------------")
print(np.linspace(1,5,21))
In [75]:
print("Vector of zeroes\n---------------------")
print(np.zeros(5))
print("Matrix of zeroes\n--------------------")
print(np.zeros((3,4))) # Notice Tuples
In [79]:
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
print("Matrix of 5's\n---------------------")
print(5*np.ones((3,5)))
In [95]:
print("Empty matrix\n-------------\n", np.empty((3,5)))
In [43]:
mat1 = np.eye(4)
print("Identity matrix of dimension", mat1.shape)
print(mat1)
In [44]:
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 Tuple is necessary
In [51]:
print("Numbers from Normal distribution with zero mean and standard deviation 1 i.e. standard normal")
print(np.random.randn(4,3))
In [49]:
print("Random integers...")
print(np.random.randint(1,100,10)) #randint (low, high, # of samples to be drawn)
print("20 samples drawn from a dice throw:",np.random.randint(1,7,20)) # 20 samples drawn from a dice throw
In [5]:
from numpy.random import randint as ri
a = ri(1,100,30)
b = a.reshape(2,3,5)
c = a.reshape(6,5)
print ("Shape of a:", a.shape)
print ("Shape of b:", b.shape)
print ("Shape of c:", c.shape)
print("\nb looks like\n",'-'*20,"\n",b,"\n",'-'*20)
print("\nc looks like\n",'-'*20,"\n",c,"\n",'-'*20)
A = ri(1,100,10) # Vector of random interegrs
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='mergesort'))
print("\nHere is the sorted matrix along each column\n",'-'*50,"\n",np.sort(M, axis=0, kind='mergesort'))
In [6]:
print("Max of a:", a.max())
print("Max of b:", b.max())
print("Max of a location:", a.argmax())
print("Max of b location:", b.argmax())
print("Max of c location:", b.argmax())
In [6]:
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])
print("3 Elements from last backwards are:", arr[-1:-6:-2])
arr = np.arange(0,21,2)
print("New array:",arr)
print("Elements at 2nd, 4th, and 9th index are:", arr[[2,4,9]]) # Pass a list as a index to subset
In [7]:
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------------------------")
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])
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]])
In [9]:
mat = np.array(ri(10,100,15)).reshape(3,5)
print("Matrix of random 2-digit numbers\n--------------------------------\n",mat)
print ("Elements greater than 50\n", mat[mat>50])
In [8]:
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----------------------------------------\n",mat1)
print("\n2nd Matrix of random single-digit numbers\n----------------------------------------\n",mat2)
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)
print("\nAddition of a scalar (100)\n-------------------------\n", 100+mat1)
print("\nExponentiation, matrix cubed here\n----------------------------------------\n", mat1**3)
print("\nExponentiation, sq-root using pow function\n-------------------------------------------\n",pow(mat1,0.5))
In [12]:
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----------------------------------------\n",mat1)
print("\n2nd Matrix of random single-digit numbers\n----------------------------------------\n",mat2)
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))
print("\nCombination of functions by shwoing exponetial decay of a sine wave\n",'-'*70)
A = np.linspace(0,12*np.pi,1001)
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()
In [54]:
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("\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","-"*80,"\n",np.std(mat1))
print("\nVariance of all numbers in the modified matrix, a larger number\n","-"*80,"\n",np.var(mat1))
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(mat2,axis=0))
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(mat1,50))
print("\n90th percentile of all numbers in the modified matrix\n","-"*60,"\n",np.percentile(mat1,90))
In [13]:
A = ri(1,5,20) # 20 random integeres from a small range (1-10)
B = 2*A+5*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")
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
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
In [46]:
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 \n","-"*50,"\n",np.dot(A,B))
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 all pairwise elements)")
print("\nOuter product of vectors A and B \n","-"*50,"\n",np.outer(A,B))
In [56]:
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(B)))
In [59]:
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))
print("\nMatrix trace with ofset +1 (upper triangle)\n","-"*50,"\n",np.trace(A,offset=1))
print("\nMatrix trace with ofset -1 (lower triangle)\n","-"*50,"\n",np.trace(A,offset=-1))