How to multiply two matrices in Python

Multiplying matrices is a common operation in linear algebra, and it can be easily performed in Python using the NumPy library. Here is a step-by-step guide on how to multiply two matrices in Python:

  1. Import the NumPy library: Start by importing the NumPy library into your Python environment. This can be done by using the following command: import numpy as np.

  2. Define the matrices: Create two matrices using the np.array() function. For example, you can create two matrices A and B as follows:

Examples: 

A = np.array([[1,2],[3,4]])
B = np.array([[5,6],[7,8]])

  1. Multiply the matrices: To multiply two matrices, simply use the np.dot() function. For example, to multiply the two matrices A and B, you can use the following command: C = np.dot(A, B). The result will be stored in the matrix C.

  2. Display the result: Finally, to display the result, simply print the matrix C. For example, you can use the following command: print(C).

That's it! You have successfully multiplied two matrices in Python using NumPy. You can now use this knowledge to perform matrix operations in your linear algebra projects.

Method 2: Matrix Multiplication Using Nested List. We use zip in Python.

 

# Program to multiply two matrices using list comprehension

# take a 3x3 matrix
A = [[12, 7, 3],
	[4, 5, 6],
	[7, 8, 9]]

# take a 3x4 matrix
B = [[5, 8, 1, 2],
	[6, 7, 3, 0],
	[4, 5, 9, 1]]

# result will be 3x4
result = [[sum(a * b for a, b in zip(A_row, B_col))
						for B_col in zip(*B)]
								for A_row in A]

for r in result:
	print(r)

Output: 

[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]

Method 3: Matrix Multiplication (Vectorized implementation). 

# Program to multiply two matrices (vectorized implementation)

# Program to multiply two matrices (vectorized implementation)
import numpy as np
# take a 3x3 matrix
A = [[12, 7, 3],
	[4, 5, 6],
	[7, 8, 9]]

# take a 3x4 matrix
B = [[5, 8, 1, 2],
	[6, 7, 3, 0],
	[4, 5, 9, 1]]

# result will be 3x4

result= [[0,0,0,0],
		[0,0,0,0],
		[0,0,0,0]]

result = np.dot(A,B)

for r in result:
	print(r)

Output: 

[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]

 

Submit Your Programming Assignment Details