Python Multiply Matrices

				
					import numpy as np
				
			
				
					# Example 1: Matrices from Slide 6
A1 = np.array([[2, 0], [1, 3]])
				
			
				
					B1 = np.array([[1, 4], [2, 5]])
				
			
				
					C1 = np.dot(A1, B1)  # Perform matrix multiplication
				
			
				
					print(C1)
				
			
				
					C1v2 = A1.dot(B1)
				
			
				
					print(C1v2)
				
			
				
					# Example 2: Random number problem matrices
A2 = np.array([[7, 4, 8], [5, 7, 3]])
				
			
				
					B2 = np.array([[7, 8], [5, 4], [8, 8]])
				
			
				
					C2 = np.dot(A2, B2)  # Perform matrix multiplication
				
			
				
					print(C2)
				
			
				
					# Function to check if two matrices can be multiplied
def can_multiply(mat1, mat2):
    if mat1.shape[1] == mat2.shape[0]:
        result_size = (mat1.shape[0], mat2.shape[1])
        print(f"Matrices of shapes {mat1.shape} and {mat2.shape} CAN be multiplied.")
        print(f"The resulting matrix will have dimensions: {result_size}")
        return result_size
    else:
        print(f"Matrices of shapes {mat1.shape} and {mat2.shape} CANNOT be multiplied.")
        return None
				
			
				
					# Example usage of the function
print("\nCan A1 and B1 be multiplied?")
can_multiply(A1, B1)
				
			
				
					print("\nCan A2 and B2 be multiplied?")
can_multiply(A2, B2)
				
			

Ryan is a Data Scientist at a fintech company, where he focuses on fraud prevention in underwriting and risk. Before that, he worked as a Data Analyst at a tax software company. He holds a degree in Electrical Engineering from UCF.

Leave a Reply

Your email address will not be published. Required fields are marked *