Matrices and grids · 5 / 15 Theory

Matrix product and sparse matrices

The matrix product combines rows of the first with columns of the second: element (i, j) is the sum of a[i][k] * b[k][j]. It can only be computed if the columns of A match the rows of B.

a = [[1, 2], [3, 4]]
b = [[0, 1], [1, 0]]

product = [[sum(x * y for x, y in zip(row, column)) for column in zip(*b)] for row in a]
print(product)                         # [[2, 1], [4, 3]]

identity = [[1 if i == j else 0 for j in range(3)] for i in range(3)]
print(identity)                        # [[1, 0, 0], [0, 1, 0], [0, 0, 1]]

# Sparse matrix: almost all zeros -> we store only what is not zero
sparse = {(0, 2): 5, (3, 1): -2, (4, 4): 7}
print(sparse.get((3, 1), 0))          # -2
print(sparse.get((1, 1), 0))          # 0   whatever is missing is zero
  • The product is not commutative: in general A·B != B·A.
  • The identity leaves a matrix intact when multiplied.
  • A sparse matrix (almost all zeros) takes less memory as a dictionary {(row, column): value}; the rest is assumed zero.
  • A magic square is a square matrix whose rows, columns and diagonals add up to the same value; it is checked by collecting all the sums.

You practice it in Matrix product and Magic square.