# Untitled

unknown
plain_text
2 months ago
2.3 kB
1
Indexable
Never
```def matrix_multiply(A, B):
# Get the number of rows and columns for matrices A and B
rows_A, cols_A = len(A), len(A[0])
rows_B, cols_B = len(B), len(B[0])

# Check if the matrices can be multiplied
if cols_A != rows_B:
raise ValueError("Number of columns in matrix A must be equal to the number of rows in matrix B.")

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

# Perform matrix multiplication
for i in range(rows_A):
for j in range(cols_B):
for k in range(cols_A):
result[i][j] += A[i][k] * B[k][j]

return result

def get_matrix_from_user(rows, cols):
matrix = []
print(f"Enter the elements for a {rows}x{cols} matrix:")
for i in range(rows):
row = []
for j in range(cols):
try:
element = float(input(f"Enter element at position ({i + 1}, {j + 1}): "))
row.append(element)
except ValueError:
print("Invalid input. Please enter a valid number.")
return get_matrix_from_user(rows, cols)
matrix.append(row)
return matrix

def print_matrix(matrix):
for row in matrix:
print(row)

def main():
try:
# Get dimensions for the first matrix
rows_A = int(input("Enter the number of rows for matrix A: "))
cols_A = int(input("Enter the number of columns for matrix A: "))

# Get dimensions for the second matrix
rows_B = int(input("Enter the number of rows for matrix B: "))
cols_B = int(input("Enter the number of columns for matrix B: "))

# Get matrices from the user
matrix_A = get_matrix_from_user(rows_A, cols_A)
matrix_B = get_matrix_from_user(rows_B, cols_B)

# Perform matrix multiplication
result_matrix = matrix_multiply(matrix_A, matrix_B)

# Display the result
print("\nMatrix A:")
print_matrix(matrix_A)
print("\nMatrix B:")
print_matrix(matrix_B)
print("\nResult of Matrix Multiplication (A * B):")
print_matrix(result_matrix)

except ValueError as e:
print(f"Error: {e}")

if __name__ == "__main__":
main()
```