Friday, October 20, 2023

Python Programming - Lab- Core Lab 5 - Bsc CS DA -Bharathiar University - Program 4 - Write a python program to find the product of two matrices [A]mxp and [B]pxr


Python Programming - Lab

Core Lab 5  

Bharathiar University 

Program 4 - Write a python program to find the product of two matrices [A]mxp and [B]pxr

Source Code

# Function to input a matrix from the user
def input_matrix(rows, cols):
matrix = []
print("Enter the matrix of size {",rows,"}x{",cols,"}:")
for i in range(rows):
r = list(map(int, input().split()))
if len(r) != cols:
print("Invalid input. Please enter exactly", cols, "numbers.")
return None
matrix.append(r)
return matrix

# Function to multiply two matrices
def multiply_matrices(A,B):
# Get dimensions of matrices A and B
m, p = len(A), len(A[0])
p, r = len(B), len(B[0])

# Check if matrices can be multiplied
if p != len(A[0]):
return "Matrices cannot be multiplied. Invalid dimensions."

# Initialize the result matrix with zeros
result = [[0 for _ in range(r)] for _ in range(m)]

# Perform matrix multiplication
for i in range(m):
for j in range(r):
for k in range(p):
result[i][j] += A[i][k] * B[k][j]

return result


# Get dimensions of matrices from the user
m = int(input("Enter the number of rows for matrix A: "))
p = int(input("Enter the number of columns for matrix A and rows for matrix B: "))
r = int(input("Enter the number of columns for matrix B: "))

# Input matrices from the user
matrix_A = input_matrix(m, p)
matrix_B = input_matrix(p, r)

# Check if input matrices are valid
if matrix_A and matrix_B:
# Calculate the product of matrices A and B
result_matrix = multiply_matrices(matrix_A, matrix_B)

# Display the result
if isinstance(result_matrix, str):
print(result_matrix) # If matrices cannot be multiplied
else:
print("Product of matrices A and B:")
for row in result_matrix:
print(row)


OUTPUT

Enter the number of rows for matrix A: 2
Enter the number of columns for matrix A and rows for matrix B: 2
Enter the number of columns for matrix B: 2
Enter the matrix of size { 2 }x{ 2 }:
1 2
1 2
Enter the matrix of size { 2 }x{ 2 }:
2 4
2 4
Product of matrices A and B:
[6, 12]
[6, 12]

No comments:

Post a Comment

Program 12 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 12 Implement a telephone directory using files

  BCA Object Oriented Programming using C++ Practical Madras University  Program 12  Implement a telephone directory using files SOURCE CODE...