Introduction
Matrix multiplication is a fundamental operation in linear algebra. Unlike element-wise operations like addition and subtraction, matrix multiplication involves combining the rows of the first matrix with the columns of the second matrix. The resulting matrix will have dimensions equal to the number of rows of the first matrix and the number of columns of the second matrix. This tutorial will guide you through creating a Python program that multiplies two matrices.
Example:
-
Matrix 1:
1 2 3 4 -
Matrix 2:
5 6 7 8 -
Resultant Matrix:
19 22 43 50
Problem Statement
Create a Python program that:
- Takes two matrices as input.
- Checks if the matrices can be multiplied (i.e., the number of columns in the first matrix equals the number of rows in the second matrix).
- Multiplies the two matrices.
- Displays the resulting matrix.
Solution Steps
- Take Matrix Dimensions: Ask the user for the number of rows and columns for both matrices.
- Initialize Two Matrices: Create two empty matrices to store the input values.
- Input Matrix Elements: Use nested loops to take input for each element of the two matrices.
- Check Multiplication Compatibility: Ensure the number of columns in the first matrix equals the number of rows in the second matrix.
- Multiply the Matrices: Use nested loops to multiply the matrices.
- Display the Resultant Matrix: Print the resulting matrix in a formatted manner.
Python Program
# Python Program to Multiply Two Matrices
# Author: https://www.rameshfadatare.com/
# Step 1: Take the number of rows and columns for the first matrix as input
rows1 = int(input("Enter the number of rows for the first matrix: "))
columns1 = int(input("Enter the number of columns for the first matrix: "))
# Step 2: Take the number of rows and columns for the second matrix as input
rows2 = int(input("Enter the number of rows for the second matrix: "))
columns2 = int(input("Enter the number of columns for the second matrix: "))
# Check if matrix multiplication is possible
if columns1 != rows2:
print("Matrix multiplication is not possible with the given dimensions.")
else:
# Step 3: Initialize the two matrices
matrix1 = []
matrix2 = []
# Step 4: Input elements for the first matrix
print("Enter the elements of the first matrix:")
for i in range(rows1):
row = []
for j in range(columns1):
element = int(input(f"Element at position ({i+1}, {j+1}): "))
row.append(element)
matrix1.append(row)
# Step 5: Input elements for the second matrix
print("Enter the elements of the second matrix:")
for i in range(rows2):
row = []
for j in range(columns2):
element = int(input(f"Element at position ({i+1}, {j+1}): "))
row.append(element)
matrix2.append(row)
# Step 6: Initialize the resultant matrix with zeros
result_matrix = []
for i in range(rows1):
result_matrix.append([0] * columns2)
# Step 7: Multiply the two matrices
for i in range(rows1):
for j in range(columns2):
for k in range(columns1):
result_matrix[i][j] += matrix1[i][k] * matrix2[k][j]
# Step 8: Display the resulting matrix
print("\nThe resultant matrix after multiplication is:")
for row in result_matrix:
for element in row:
print(element, end=" ")
print() # Newline after each row
Explanation
Step 1: Take the Number of Rows and Columns for the First Matrix as Input
- The
input()function is used to take the number of rows and columns for the first matrix. These values are converted to integers and stored inrows1andcolumns1variables.
Step 2: Take the Number of Rows and Columns for the Second Matrix as Input
- The process is repeated to take the number of rows and columns for the second matrix, which are stored in
rows2andcolumns2.
Step 3: Check Multiplication Compatibility
- Matrix multiplication is only possible if the number of columns in the first matrix equals the number of rows in the second matrix. If this condition is not met, the program will print an error message and terminate.
Step 4: Input Elements for the First and Second Matrices
- Nested loops are used to take input for each element of the first and second matrices. The elements are stored in
matrix1andmatrix2, respectively.
Step 5: Initialize the Resultant Matrix with Zeros
- A new matrix
result_matrixis initialized with zeros. This matrix will store the product ofmatrix1andmatrix2.
Step 6: Multiply the Two Matrices
- Three nested loops are used to perform matrix multiplication:
- The outer loop iterates over the rows of the first matrix.
- The middle loop iterates over the columns of the second matrix.
- The inner loop iterates over the elements being multiplied and adds the products to the appropriate position in the resultant matrix.
Step 7: Display the Resulting Matrix
- The resulting matrix is displayed using a nested loop, with each row printed on a new line.
Output Example
Example Output:
Enter the number of rows for the first matrix: 2
Enter the number of columns for the first matrix: 2
Enter the number of rows for the second matrix: 2
Enter the number of columns for the second matrix: 2
Enter the elements of the first matrix:
Element at position (1, 1): 1
Element at position (1, 2): 2
Element at position (2, 1): 3
Element at position (2, 2): 4
Enter the elements of the second matrix:
Element at position (1, 1): 5
Element at position (1, 2): 6
Element at position (2, 1): 7
Element at position (2, 2): 8
The resultant matrix after multiplication is:
19 22
43 50
Additional Examples
Example 1: Multiplying a 3×2 Matrix by a 2×3 Matrix
# Example of multiplying a 3x2 matrix by a 2x3 matrix
rows1 = 3
columns1 = 2
matrix1 = [
[1, 4],
[2, 5],
[3, 6]
]
rows2 = 2
columns2 = 3
matrix2 = [
[7, 8, 9],
[10, 11, 12]
]
# Resultant matrix initialization
result_matrix = [[0 for _ in range(columns2)] for _ in range(rows1)]
# Multiplying matrices
for i in range(rows1):
for j in range(columns2):
for k in range(columns1):
result_matrix[i][j] += matrix1[i][k] * matrix2[k][j]
# Displaying the resultant matrix
print("\nThe resultant matrix after multiplication is:")
for row in result_matrix:
for element in row:
print(element, end=" ")
print()
Output:
The resultant matrix after multiplication is:
47 52 57
64 71 78
81 90 99
Example 2: Multiplying Two Matrices with Negative Numbers
# Example with negative numbers
matrix1 = [
[-1, 2],
[3, -4]
]
matrix2 = [
[5, -6],
[-7, 8]
]
rows1 = 2
columns1 = 2
rows2 = 2
columns2 = 2
result_matrix = [[0 for _ in range(columns2)] for _ in range(rows1)]
# Multiplying matrices
for i in range(rows1):
for j in range(columns2):
for k in range(columns1):
result_matrix[i][j] += matrix1[i][k] * matrix2[k][j]
# Displaying the resultant matrix
print("\nThe resultant matrix is:")
for row in result_matrix:
for element in row:
print(element, end=" ")
print()
Output:
The resultant matrix is:
-19 22
43 -50
Conclusion
This Python program demonstrates how to multiply two matrices by taking input from the user for each matrix’s elements. The program then multiplies the two matrices and displays the resulting matrix. Understanding matrix multiplication is fundamental for performing operations in linear algebra and various computational tasks in Python.