Skip to Main Content
Blog

Add Two Matrix in Python

Add Two Matrix in Python

def main():
	"""
	Prints the sum of two matrices.
	"""

	# Get the dimensions of the matrices
	row_count = int(input("Enter the number of rows in the matrices: "))
	col_count = int(input("Enter the number of cols in the matrices: "))

	# Read the matrices from the user
	print("Enter matrix A:")
	a = read_matrix(row_count, col_count)
	print("Enter matrix B:")
	b = read_matrix(row_count, col_count)

	# Sum the matrices together
	c = add(a, b)

	# Print the result
	print("The sum is:")
	print_matrix(c)


def add(x: list[list[int]], y: list[list[int]]):
	"""
	Returns the sum of two matrices.
	"""

	# Get the dimensions of the matrices
	rows_x, cols_x = len(x), len(x[0])
	rows_y, cols_y = len(y), len(y[0])

	# Check if the matrices can be added
	if rows_x != rows_y or cols_x != cols_y:
		raise ValueError("Both matrices must have the same dimensions.")

	# Initialize the result matrix with zeros
	z = [[0] * cols_x for _ in range(rows_x)]

	# Iterate over the matrices and sum
	for r in range(rows_x):
		for c in range(cols_x):
			z[r][c] = x[r][c] + y[r][c]

	return z


def read_matrix(row_count: int, col_count: int):
	"""
	Reads a matrix from the console.
	"""

	matrix: list[list[int]] = []
	for _ in range(row_count):
		row = list(map(int, input().split()[:col_count]))
		matrix.append(row)

	return matrix


def print_matrix(matrix: list[list[int]]):
	"""
	Prints a matrix to the console.
	"""

	for row in matrix:
		for element in row:
			print(element, end=" ")
		print()


if __name__ == "__main__":
	main()