In fields like image processing and machine learning, data is frequently handled as “matrices,” and calculations often involve adding or multiplying these matrices together. By using NumPy, you can implement these operations with simple code that resembles mathematical formulas, without the need to write complex loops.
Here, I will explain the correct implementation methods for “addition and subtraction” using two matrices, as well as the mathematical “matrix multiplication (dot product).”
1. Matrix Addition and Subtraction
Addition and subtraction between matrices follow a simple rule: “calculate the numbers at the same position” (element-wise operation). You can perform these calculations by simply using Python’s standard + and - operators.
Sample Code
Here, we define two 2×2 matrices, X and Y, and perform the calculations.
Python
import numpy as np
def matrix_basic_calc():
# Define Matrix X
X = np.array([
[5, 10],
[2, 4]
])
# Define Matrix Y
Y = np.array([
[3, 1],
[1, 2]
])
print("--- Matrix X ---")
print(X)
print("--- Matrix Y ---")
print(Y)
# Addition (X + Y)
# Top-left element: 5 + 3 = 8
print("\n[Addition: X + Y]")
add_result = X + Y
print(add_result)
# Subtraction (X - Y)
# Top-left element: 5 - 3 = 2
print("\n[Subtraction: X - Y]")
sub_result = X - Y
print(sub_result)
if __name__ == "__main__":
matrix_basic_calc()
Execution Result
Plaintext
--- Matrix X ---
[[ 5 10]
[ 2 4]]
--- Matrix Y ---
[[3 1]
[1 2]]
[Addition: X + Y]
[[ 8 11]
[ 3 6]]
[Subtraction: X - Y]
[[2 9]
[1 2]]
2. Matrix Multiplication (Dot Product)
The most common mistake in matrix calculations is “multiplication.” If you simply write X * Y, it results in “element-wise multiplication,” just like addition.
To perform “matrix multiplication” (calculating the sum of the product of rows and columns) in the mathematical sense, you must use the np.dot() function.
Sample Code
Python
import numpy as np
def matrix_dot_product():
# Matrix A
A = np.array([
[1, 2],
[3, 4]
])
# Matrix B
B = np.array([
[5, 6],
[7, 8]
])
# Calculating Matrix Product: np.dot(A, B)
# Calculation Logic (Top-left value): (1 * 5) + (2 * 7) = 5 + 14 = 19
dot_result = np.dot(A, B)
print("--- Matrix Product (np.dot) ---")
print(dot_result)
# [Note] New syntax for Python 3.5 and later
# Using the @ operator makes it look more like a mathematical formula
dot_result_new = A @ B
print("\n--- Matrix Product (@ Operator) ---")
print(dot_result_new)
if __name__ == "__main__":
matrix_dot_product()
Execution Result
Plaintext
--- Matrix Product (np.dot) ---
[[19 22]
[43 50]]
--- Matrix Product (@ Operator) ---
[[19 22]
[43 50]]
Summary
- Addition/Subtraction: Use
+and-(calculated element by element). - Multiplication: Use
np.dot()or@for matrix calculations. Do not use*.
The difference in multiplication is a frequent cause of bugs. This is one of the most important points to understand when using NumPy.
