Matrix calculator library in C++
Write your own Matrix class with +, −, ×, transpose, determinant and inverse, with tests, like a tiny NumPy.
Intermediate⏱ 6–10 hours🪜 7 stepsC++ClassesOperator overloading
What you'll learn
- ◆Classes, constructors and RAII
- ◆Operator overloading and exceptions
- ◆Gaussian elimination
What you'll build
- ✓Matrix a(3,3); a + b, a * b, a.T()
- ✓Determinant and inverse
- ✓Throws on size mismatch
- ✓Unit tests
Step-by-step guide
- 1
Store data
class Matrix { size_t r, c; std::vector<double> d; } with at(i, j) returning d[i*c + j].
- 2
Constructors and printing
Constructor from sizes, from an initializer_list of rows, and operator<< for printing.
- 3
Operators
Implement operator+, operator- and operator* (check sizes, throw std::invalid_argument on mismatch).
- 4
Transpose and identity
T() swaps indices; static identity(n).
- 5
Determinant
Use Gaussian elimination with partial pivoting; track row swaps to fix the sign; O(n³) instead of recursion.
- 6
Inverse
Gauss-Jordan on [A | I]; throw if a pivot is (close to) zero, meaning the matrix is singular.
- 7
Tests
Use a header-only test library (doctest or Catch2) to check A * inverse(A) ≈ I within 1e-9.
🚀 Make it stand out
- +Make it a template Matrix<T>
- +Solve linear systems Ax = b
- +Benchmark against a naive version