Matrix operations and linear systems

2.5.5

Multiply matrices and solve a system of linear equations with NumPy.

On this page

Matrix and vector multiplication

For a 2D matrix with n columns, a 1D vector of length n can be multiplied using @. The result has one value per matrix row. Verify compatible shapes before combining arrays.

import numpy as np

costs = np.array([[2, 1], [4, 2]])
prices = np.array([3, 5])
print((costs @ prices).tolist())
Example output
[11, 22]

Solve a linear system

Use linalg.solve for a square full-rank system A @ x = b. For a rectangular system, consider least squares. Check whether the computed solution approximately satisfies the original equation.

import numpy as np

A = np.array([[2, 1], [1, -1]])
b = np.array([7, 2])
x = np.linalg.solve(A, b)
print(x.round(2).tolist())
print(np.allclose(A @ x, b))
Example output
[3.0, 1.0]
True

Official references