Skip to content

Instantly share code, notes, and snippets.

@sshehrozali
Created November 25, 2020 17:38
Show Gist options
  • Save sshehrozali/73d296f492e4bf9966cc13dd31f91203 to your computer and use it in GitHub Desktop.
Save sshehrozali/73d296f492e4bf9966cc13dd31f91203 to your computer and use it in GitHub Desktop.
Program to multiply 2x2 matrices.
# Program to multiply 2x2 matrices. Developed By Syed Shehroz Ali #
# Welcome Line
print("\n---| Multiplication of 2x2 Matrices | ---\n")
# 2D List for matrices
A = [[], []]
B = [[], []]
# Ask for Matrix A values
print("\tMATRIX A\n\t--------\n")
for row in range(2):
# For each row, get 2 column values
column1, column2 = input("\t").split()
# Insert into nested list
A[row].insert(0, eval(column1))
A[row].insert(1, eval(column2))
# Ask for Matrix B values
print("\n\tMATRIX B\n\t--------\n")
for row in range(2):
# For each row, get 2 column values
column1, column2 = input("\t").split()
# Insert into nested list
B[row].insert(0, eval(column1))
B[row].insert(1, eval(column2))
# Print A x B
print("\n\tA x B\n\t--------\n")
# 2D List to store A x B
matrix = [[], []]
# For each row
for row in range(2):
# For each column
for column in range(2):
# 1st Iteration
if row == 0 and column == 0:
val = (A[row][column] * B[row][column]) + (A[row][column + 1] * B[row + 1][column])
matrix[row].insert(column, val)
# 2nd Iteration
if row == 0 and column == 1:
val = (A[row][column - 1] * B[row][column]) + (A[row][column] * B[row + 1][column])
matrix[row].insert(column, val)
# 3rd Iteration
if row == 1 and column == 0:
val = (A[row][column] * B[row - 1][column]) + (A[row][column + 1] * B[row][column])
matrix[row].insert(column, val)
# 4th Iteration
if row == 1 and column == 1:
val = (A[row][column - 1] * B[row - 1][column]) + (A[row][column] * B[row][column])
matrix[row].insert(column, val)
# Print whole matrix (A x B)
for row in matrix:
for column in row:
print("\t", end="")
print(column, end="")
print()
# Print new-line, end.
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment