linear-algebra

Linear System Ax = b

MATLAB's backslash operator `A\b` — solve a linear system the way every engineer learned.

The backslash operator is where MATLAB is at its most elegant. `np.linalg.solve(A, b)` does the same thing with a function call. For over- or under-determined systems, MATLAB transparently switches between LU, QR, and least-squares; numpy requires you to know which solver you want. Our converter picks `solve` for square systems and flags non-square with a TODO.

MATLAB source8 lines
% Solve a system of linear equations
A = [3 2 -1; 2 -2 4; -1 0.5 -1];
b = [1; -2; 0];

x = A \ b;

fprintf('Solution: x = [%.4f, %.4f, %.4f]\n', x(1), x(2), x(3));
fprintf('Residual: %.2e\n', norm(A*x - b));
Python output (converter-generated)11 lines · 0 flags
import numpy as np

# Solve a system of linear equations
A = np.array([[3, 2, -1], [2, -2, 4], [-1, 0.5, -1]])
b = np.array([[1], [-2], [0]])

x = np.linalg.solve(A, b)

print('Solution: x = [%.4f, %.4f, %.4f]' % (x[0], x[1], x[2]))
print('Residual: %.2e' % (np.linalg.norm(A*x - b),))
Implementation notes
np.linalg.solve requires a square matrix. For rectangular A, use np.linalg.lstsq(A, b, rcond=None)[0].
Try it on your own MATLAB

Free for 50 lines. Same converter that produced the Python above.

More examples like this, once a week

New canonical conversions and release notes from the converter. One email, no spam.