import numpy as np # Create a matrix will all elements as 1 from Display_Shape import display_shape ones_matrix = np.ones((3, 3)) display_shape(ones_matrix) # Create a matrix with all elements as 0 zeros_matrix = np.zeros((3, 3)) display_shape(zeros_matrix) # Identity matrix # k parameter controls the index of 1 # if k =0, (0,0),(1,1,),(2,2) cell values # are set to 1 in a 3 x 3 matrix identity_matrix = np.eye(N=3, M=3, k=0) display_shape(identity_matrix) identity_matrix = np.eye(N=3, k=1) display_shape(identity_matrix)
# Alternate ways of creating arrays # 1. Leverage np.arange to create numpy array import numpy as np from Display_Shape import display_shape created_array = np.arange(1, 10, dtype=float) display_shape(created_array) # 2. Using np.linspace to create numpy array created_array = np.linspace(1, 10) display_shape(created_array) # 3. Create numpy arrays in using np.logspace created_array = np.logspace(1, 10, base=10.0) display_shape(created_array) # Specify step size in arange while creating # an array. This is where it is different # from np.linspace created_array = np.arange(1, 10, 2, dtype=int) display_shape(created_array)
# Array shaping from Display_Shape import display_shape import numpy as np a_matrix = np.arange(9).reshape(3, 3) display_shape(a_matrix) # Paramter -1 refers to as many as dimension needed back_to_array = a_matrix.reshape(-1) display_shape(back_to_array) a_matrix = np.arange(9).reshape(3, 3) back_array = np.ravel(a_matrix) display_shape(back_array) a_matrix = np.arange(9).reshape(3, 3) back_array = a_matrix.flatten() display_shape(back_array)
# Addition c_matrix = a_matrix + b_matrix # Element wise multiplication d_matrix = a_matrix * b_matrix # matrix multiplication e_matrix = np.dot(a_matrix, b_matrix) # matrix tranpsose f_matrix = e_matrix.T # min,max,sum print print "f_matrix,minimum = %d" % (f_matrix.min()) print "f_matrix,maximum = %d" % (f_matrix.max()) print "f_matrix, col sum", f_matrix.sum(axis=0) print "f_matrix, row sum", f_matrix.sum(axis=1) display_shape(f_matrix[::-1]) # Like python all elements are used by reference # if copy is needed copy() command is used f_copy = f_matrix.copy() # Grid commands xx, yy, zz = np.mgrid[0:3, 0:3, 0:3] xx = xx.flatten() yy = yy.flatten() zz = zz.flatten()
import numpy as np # Creating matrices from Display_Shape import display_shape a_listoflist = [[1, 2, 3], [5, 6, 7], [8, 9, 10]] a_matrix = np.matrix(a_listoflist, dtype=float) display_shape(a_matrix)