Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program multiplication of two matrix.
Matrix multiplication is a fundamental operation in linear algebra where we multiply two matrices to produce a resultant matrix. In Python, we can implement matrix multiplication using nested loops and list comprehensions.
Algorithm
Step 1: Input two matrices of compatible dimensions Step 2: Initialize a result matrix with zeros Step 3: Use three nested loops: - Outer loop for rows of first matrix - Middle loop for columns of second matrix - Inner loop for dot product calculation Step 4: For each position (i,j), multiply corresponding elements and sum them Step 5: Display the resultant matrix
Matrix Multiplication Rules
For matrix multiplication to be possible, the number of columns in the first matrix must equal the number of rows in the second matrix. The resulting matrix will have dimensions equal to the rows of the first matrix and columns of the second matrix.
Example Code
# Program to multiply two matrices
def input_matrix(name):
"""Function to input a matrix from user"""
n = int(input(f"Enter N for N x N matrix {name}: "))
matrix = []
print(f"Enter elements for matrix {name}:")
for i in range(n):
row = []
for j in range(n):
element = int(input(f"Element [{i}][{j}]: "))
row.append(element)
matrix.append(row)
return matrix, n
def display_matrix(matrix, name):
"""Function to display matrix in proper format"""
print(f"Matrix {name}:")
for row in matrix:
for element in row:
print(f"{element:3}", end=" ")
print()
def multiply_matrices(A, B, n):
"""Function to multiply two matrices"""
result = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
result[i][j] += A[i][k] * B[k][j]
return result
# Input first matrix
matrix_A, n = input_matrix("A")
display_matrix(matrix_A, "A")
# Input second matrix
matrix_B, _ = input_matrix("B")
display_matrix(matrix_B, "B")
# Multiply matrices
result = multiply_matrices(matrix_A, matrix_B, n)
# Display result
print("\nResultant Matrix (A × B):")
display_matrix(result, "Result")
Simplified Example with Predefined Matrices
# Matrix multiplication with predefined matrices
A = [[2, 1, 4],
[2, 1, 2],
[3, 4, 3]]
B = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# Initialize result matrix
result = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
# Matrix multiplication
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
print("Matrix A:")
for row in A:
print(row)
print("\nMatrix B:")
for row in B:
print(row)
print("\nResultant Matrix (A × B):")
for row in result:
print(row)
Matrix A: [2, 1, 4] [2, 1, 2] [3, 4, 3] Matrix B: [1, 2, 3] [4, 5, 6] [7, 8, 9] Resultant Matrix (A × B): [34, 41, 48] [20, 25, 30] [40, 50, 60]
Using NumPy for Matrix Multiplication
import numpy as np
# Define matrices using NumPy
A = np.array([[2, 1, 4],
[2, 1, 2],
[3, 4, 3]])
B = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Matrix multiplication using NumPy
result = np.dot(A, B)
# Alternative: result = A @ B
print("Matrix A:")
print(A)
print("\nMatrix B:")
print(B)
print("\nResultant Matrix:")
print(result)
Matrix A: [[2 1 4] [2 1 2] [3 4 3]] Matrix B: [[1 2 3] [4 5 6] [7 8 9]] Resultant Matrix: [[34 41 48] [20 25 30] [40 50 60]]
Conclusion
Matrix multiplication can be implemented using nested loops in pure Python or efficiently using NumPy's built-in functions. The key is ensuring compatible dimensions and correctly implementing the dot product calculation for each position in the result matrix.
