Sub topic 9
Matrix Addition and Scalar Multiplication
This chapter assumes you can build and index a nested list, write nested for loops, and use list comprehensions. Both operations here are element-wise: each result cell depends only on the cell at the same position in the inputs.
The working model
A matrix with m rows and n columns has shape m by n. Two operations take one or two matrices and return a new matrix of the same shape.
- Matrix addition adds cells at the same position:
result[r][c] = a[r][c] + b[r][c]. Both matrices must have the same shape. - Scalar multiplication multiplies every cell by one number:
result[r][c] = k * a[r][c]. Any shape works.
For example:
| Operation | Input | Result |
|---|---|---|
| A + B | A = [[1, 2], [3, 4]], B = [[10, 20], [30, 40]] | [[11, 22], [33, 44]] |
| 3 * A | A = [[1, 2], [3, 4]] | [[3, 6], [9, 12]] |
Implementing addition
Check the shapes first, then build a new matrix. Building a fresh result avoids changing the inputs, and a comprehension gives each row its own list, so rows are not shared.
def mat_add(a, b):
if len(a) != len(b) or any(len(ra) != len(rb) for ra, rb in zip(a, b)):
raise ValueError("matrices must have the same shape")
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
A = [[1, 2], [3, 4]]
B = [[10, 20], [30, 40]]
print(mat_add(A, B)) # [[11, 22], [33, 44]]The check compares each row length, not only len(a[0]). This also catches jagged inputs, where rows differ in length.
Implementing scalar multiplication
def scale(k, a):
return [[k * x for x in row] for row in a]
A = [[1, 2], [3, 4]]
print(scale(3, A)) # [[3, 6], [9, 12]]
print(scale(-1, A)) # [[-1, -2], [-3, -4]]Subtraction follows from these two operations: A - B equals mat_add(A, scale(-1, B)).
Properties worth knowing
These hold for same-shaped matrices and are useful for testing your code:
- Addition is commutative:
A + B == B + A. - Addition is associative:
(A + B) + C == A + (B + C). - Scaling distributes over addition:
k * (A + B) == k*A + k*B. - Adding a zero matrix (all cells 0) returns the original matrix.
Floating-point values can break exact equality in the associative and distributive checks because of rounding. Use integers in tests, or compare with a tolerance such as math.isclose.
Common errors
- Using
+on nested lists.A + Bconcatenates the lists into[[1, 2], [3, 4], [10, 20], [30, 40]]. It does not add cells. - Using
*on a nested list.A * 3repeats the list three times. It does not scale values. - Skipping the shape check.
zipstops at the shorter input, so mismatched shapes silently drop data instead of raising an error. - Modifying an input in place by accident. If you write into
aand return it, the caller's matrix changes too. Return a new matrix unless in-place update is the documented behavior.
Cost
Both operations visit each of the m times n cells once, so time is O(m·n). The result takes O(m·n) extra space because it is a new matrix. In-place versions use O(1) extra space but overwrite the original.
Exercise
Write mat_sub(a, b) that returns the cell-wise difference of two same-shaped matrices without writing a second pair of loops. What does mat_sub([[5, 5]], [[1, 2]]) return?
Show answer
Reuse the existing functions: def mat_sub(a, b): return mat_add(a, scale(-1, b)). The call returns [[4, 3]], because scaling [[1, 2]] by -1 gives [[-1, -2]], and adding that to [[5, 5]] gives [[4, 3]].
Exercise
A 1000 by 500 matrix is added to another matrix of the same shape. How many cell additions happen, and what is the time complexity?
Show answer
1000 × 500 = 500,000 additions. The time complexity is O(m·n), which here is linear in the number of cells.