Skip to content
C++ project #12Intermediate

Matrix Calculator

A value-semantic Matrix class with overloaded operators, determinant, inverse, rank and transpose, driven by a small command language.

Estimated time
~5 hours to build
Files
7 files · 505 lines
Technologies
C++17, <vector>, <cmath>, <stdexcept>, Header/source split

Introduction

Operator overloading shines when the operations already have familiar symbols, and matrices are the classic case. This project builds a Matrix class stored in one contiguous vector, implements +, -, * (matrix and scalar) the idiomatic way via compound operators, and adds Gaussian elimination for the determinant, rank and inverse.

Problem statement

Write a calculator where users define named matrices (let A 2 2 4 7 2 6) and evaluate operations: addition, subtraction, multiplication by a matrix or a number, determinant, inverse, transpose, rank and equality. Results are stored in ans. Shape mismatches, singular matrices and unknown names must produce clear errors.

Objectives

  • Overload arithmetic operators in terms of compound assignment
  • Store a 2D structure in a 1D std::vector
  • Implement Gaussian and Gauss-Jordan elimination with partial pivoting
  • Use a custom exception type derived from std::invalid_argument

Features

  • Named matrices and an ans register
  • Matrix and scalar multiplication
  • Determinant, inverse, rank, transpose, equality with tolerance
  • Shape-checked operations with readable errors

Concepts demonstrated

  • Operator overloading
  • Value semantics
  • Custom exceptions
  • Numerical algorithms
  • Floating-point tolerance

System architecture

Matrix keeps rows_, cols_ and a row-major std::vector<double>; operator()(r, c) indexes it. operator+=/-=/*= do the work and the binary operators take their left operand by value and return the modified copy. A shared eliminate helper row-reduces a copy and returns the number of row swaps, which gives the determinant's sign; rank counts pivots; inverse runs Gauss-Jordan on an augmented identity. DimensionError signals shape mismatches; std::domain_error signals a singular matrix.

Folder structure

TextProject tree
matrix-calculator/
├── README.md
├── Makefile
├── src/main.cpp
├── src/matrix.cpp
├── src/matrix.h
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

Makefile

20 lines
MakefileMakefile
# Generated for KENHOLT Skills. Usage: make | make test | make clean
CXX = g++
CXXFLAGS = -std=c++17 -Wall -Wextra -O2
SRC := $(wildcard src/*.cpp)
HDR := $(wildcard src/*.h src/*.hpp)
ARGS := $(shell cat tests/args.txt 2>/dev/null)
INPUT := $(wildcard tests/sample-input.txt)
app: $(SRC) $(HDR)
$(CXX) $(CXXFLAGS) -Isrc $(SRC) -o app
test: app
./app $(ARGS) $(if $(INPUT),< $(INPUT),) > actual.txt
diff actual.txt tests/expected-output.txt && echo "Test passed: output matches tests/expected-output.txt"
clean:
rm -f app app.exe actual.txt
.PHONY: test clean

What each file does

src/matrix.h
The Matrix interface, free operator declarations and the DimensionError exception type.
src/matrix.cpp
Storage, arithmetic, elimination-based determinant/rank, Gauss-Jordan inverse and the << printer.
src/main.cpp
The command language: let, binary expressions, det, inv, T, rank, show, eq, vars.
Makefile
Build automation: make builds ./app, make test runs the sample session and compares it with the expected output, make clean removes build files.

How to run it

Build

Terminal
g++ -std=c++17 -Wall -Wextra -Isrc src/*.cpp -o app
# or simply: make

Run

Terminal
./app # Linux / macOS
.\app.exe # Windows

Test against the expected output

Terminal
./app < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt # no output means they match
# Windows PowerShell:
# Get-Content tests\sample-input.txt | .\app.exe > actual.txt
# Compare-Object (Get-Content actual.txt) (Get-Content tests\expected-output.txt)

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
=== Matrix Calculator ===
> A =
[ 4.000 7.000 ]
[ 2.000 6.000 ]
> B =
[ 1.000 2.000 ]
[ 3.000 4.000 ]
> C =
[ 1.000 2.000 3.000 ]
[ 4.000 5.000 6.000 ]
> S =
[ 1.000 2.000 3.000 ]
[ 4.000 5.000 6.000 ]
[ 7.000 8.000 9.000 ]
> Error: expected 4 numbers
> ans =
[ 5.000 9.000 ]
[ 5.000 10.000 ]
> ans =
[ 25.000 36.000 ]
[ 20.000 28.000 ]
> ans =
[ 32.000 43.000 54.000 ]
[ 26.000 34.000 42.000 ]
> Error: cannot multiply 2x3 by 2x2 (inner sizes differ)
> ans =
[ 2.000 3.500 ]
[ 1.000 3.000 ]
> det A = 10
> ans =
[ 0.600 -0.700 ]
[ -0.200 0.400 ]
> ans =
[ 1.000 0.000 ]
[ 0.000 1.000 ]
> I =
[ 1.000 0.000 ]
[ 0.000 1.000 ]
> equal
> det S = 0
> rank S = 2
> Error: matrix is singular (determinant 0), so it has no inverse
> ans =
[ 1.000 4.000 ]
[ 2.000 5.000 ]
[ 3.000 6.000 ]
> Error: determinant needs a square matrix, not 2x3
> Error: no matrix named 'X'
>
Input
let A 2 2 4 7 2 6
let B 2 2 1 2 3 4
let C 2 3 1 2 3 4 5 6
let S 3 3 1 2 3 4 5 6 7 8 9
let D 2 2 1 2 3
A + B
A * B
A * C
C * A
A * 0.5
det A
inv A
A * ans
let I 2 2 1 0 0 1
eq ans I
det S
rank S
inv S
T C
det C
inv X
quit

Testing

  • Compare ./app < tests/sample-input.txt with tests/expected-output.txt.
  • det A = 4·6 − 7·2 = 10, and A × inv A equals the identity (eq ans I prints equal).
  • The 3×3 matrix 1..9 has determinant 0 and rank 2, so inv S fails.
  • 2×3 × 2×2 is rejected because the inner sizes differ.

Common errors

Inverse contains huge numbers or NaN

Use partial pivoting (choose the largest absolute value in the column) and treat values below a small epsilon as zero.

Prints -0.000

Floating-point results can be tiny negatives; snap values close to zero to 0.0 before printing.

Possible improvements

  • Solve linear systems Ax = b
  • Parse full expressions such as A * B + C
  • Support exact fractions using the Fraction Calculator class

Additional challenges

  1. 1Add matrix powers A ^ n using repeated squaring.
  2. 2Implement LU decomposition and reuse it for det and inverse.
  3. 3Template the class on the element type.

Built and tested it yourself? Mark it to update your dashboard.