Whenever I study mathematics, whether for college or self-study, I've always had this tendency to code the process behind how calculations are made. In other words, I like building small programs that automate mathematical operations. During my recent midterm examinations, I had the fun idea to create a program that performs matrix operations automatically: addition, subtraction, multiplication, scalar multiplication, and even detecting whether a matrix is an identity matrix or not.
Programming these processes requires a solid understanding of the underlying math. You need to grasp the logic behind each operation before you can translate it into code. Writing these algorithms myself helped me deepen my understanding of how to perform the operations by hand, which ended up helping me a lot during my midterms last week.
Here's an example of a Python program I created to review for my midterms in Computer Graphics:
def main() -> None:
# Expected output: [[6, 8], [10, 12]]
print(matrix_addition([[1, 2], [3, 4]], [[5, 6], [7, 8]]))
# Expected output: [[2, -2], [1, 5]]
print(matrix_subtraction([[4, 2], [1, 6]], [[2, 4], [0, 1]]))
# Expected output: [[2, 4], [6, 8]]
print(scalar_multiplication(2, [[1, 2], [3, 4]]))
# Expected output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
print(transpose_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
# Expected output: True
print(is_identity_matrix([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]]))
# Expected output: False
print(is_identity_matrix([[1, 0, 0, 0],
[0, 1, 2, 0],
[0, 0, 1, 0],
[0, 3, 0, 1]]))
# Expected output:[[50, 42, 42], [25, 96, 26]]
print(matrix_multiplication([[3, 2, 1, 5], [9, 1, 3, 0]], [
[2, 9, 0], [1, 3, 5], [2, 4, 7], [8, 1, 5]]))
def matrix_addition(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]:
return matrix_arithmetic(matrix_a, matrix_b, True)
def matrix_subtraction(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]:
return matrix_arithmetic(matrix_a, matrix_b, False)
def matrix_arithmetic(matrix_a: list[list[int]], matrix_b: list[list[int]], is_addition: bool) -> list[list[int]]:
output = []
for i in range(len(matrix_a)):
row = []
for j in range(len(matrix_a[i])):
row.append(matrix_a[i][j] + matrix_b[i][j]
if is_addition else matrix_a[i][j] - matrix_b[i][j])
output.append(row)
return output
def scalar_multiplication(scalar: int, matrix: list[list[int]]) -> list[list[int]]:
output = []
for i in range(len(matrix)):
row = []
for j in range(len(matrix[i])):
row.append(scalar * matrix[i][j])
output.append(row)
return output
def is_identity_matrix(matrix: list[list[int]]) -> list[list[int]]:
for i in range(len(matrix)):
for j in range(len(matrix[i])):
cell = matrix[i][j]
if (i == j and cell != 1) or (i != j and cell != 0):
return False
return True
def transpose_matrix(matrix: list[list[int]]) -> list[list[int]]:
output = []
for i in range(len(matrix)):
row = []
for j in range(len(matrix[i])):
row.append(matrix[j][i])
output.append(row)
return output
def matrix_multiplication(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]:
output = []
for i in range(len(matrix_a)):
row = []
for j in range(len(matrix_b[0])):
cell_sum = 0
for k in range(len(matrix_b)):
cell_sum += matrix_a[i][k] * matrix_b[k][j]
row.append(cell_sum)
output.append(row)
return output
if __name__ == "__main__":
main()
It's important not to rely on AI to generate these algorithms if you plan on studying this way yourself. Doing so defeats the purpose of learning, since the goal is to engage your brain in the process of understanding and internalizing the logic behind each step. For me, the learning happens when I code the algorithms manually, without external assistance.
I know there are shorter or more optimized ways to write these programs, but I chose to code them imperatively to get a clearer view of how each step in the mathematical process unfolds.
Here's another example of a Python program I created for my Computer Graphics midterms, this one focuses on scaling and translation:
def main() -> None:
print("Welcome to the Scaling and Translation Calculator by Marc Plarisan!")
print("This program allows you to perform scaling and translation on 3D points.")
print("===============================================================")
execute_menu()
def execute_menu() -> None:
commands = ["scale", "translation"]
EXIT_WORD = "exit"
print(f"Type '{EXIT_WORD}' to exit the program.")
while True:
print("Commands:")
for command in commands:
print(f" - {command}")
user_input = input("Enter a command: ").lower().strip()
if user_input == EXIT_WORD:
print("Exiting the program.")
break
if user_input == "scale":
try:
x = int(input("Enter scaling factor for x: "))
y = int(input("Enter scaling factor for y: "))
z = int(input("Enter scaling factor for z: "))
values = tuple(
int(i) for i in input("Enter the point (x, y, z) separated by spaces: ").split()
)
if len(values) != 3:
raise ValueError(
"You must enter exactly three integers for the point."
)
result = scale(x, y, z, values)
print(f"=========> Scaled point: {result} <=========")
except ValueError as e:
print(f"Invalid input: {e}")
elif user_input == "translation":
try:
x = int(input("Enter translation value for x: "))
y = int(input("Enter translation value for y: "))
z = int(input("Enter translation value for z: "))
values = tuple(
int(i) for i in input("Enter the point (x, y, z) separated by spaces: ").split()
)
if len(values) != 3:
raise ValueError(
"You must enter exactly three integers for the point."
)
result = translation(x, y, z, values)
print(f"=========> Translated point: {result} <=========")
except ValueError as e:
print(f"Invalid input: {e}")
else:
print("Unknown command. Please try again.")
def scale(x: int, y: int, z: int, values: tuple[int, int, int]) -> list[int]:
values = (*values, 1)
matrix = [
[x, 0, 0, 0],
[0, y, 0, 0],
[0, 0, z, 0],
[0, 0, 0, 1],
]
return [sum(row[i] * values[i] for i in range(4)) for row in matrix]
def translation(x: int, y: int, z: int, values: tuple[int, int, int]) -> list[int]:
matrix = [
[x, 0, 0, values[0]],
[0, y, 0, values[1]],
[0, 0, z, values[2]],
[0, 0, 0, 1],
]
output = []
for row in matrix:
output.append(sum(row))
return output
if __name__ == "__main__":
main()
I find this method of studying both fun and effective. It allows me to understand mathematical concepts more deeply while improving my programming skills at the same time. I've written several more programs for other math topics, all of which you can find on my GitHub profile. The ones I've shared here are just a small sample.
Anyway, I just wanted to share this learning method and hopefully inspire others to explore it as well.
