Introduction
Linear algebra powers graphics, machine learning and engineering simulations. This toolkit implements the core matrix operations in C with heap-allocated, contiguous storage — the same layout numeric libraries use.
Problem statement
Objectives
- Store a 2D matrix in a single malloc'd block
- Implement elimination algorithms with partial pivoting
- Return results by value with an error convention
- Manage memory for many temporary matrices without leaks
Features
- Any size up to 20 × 20
- Dimension checks for addition and multiplication
- Determinant with row-swap sign tracking
- Inverse with singularity detection and automatic verification
Concepts demonstrated
- Row-major storage
- Gaussian elimination
- Numerical stability
- Ownership of returned structs
System architecture
Matrix holds rows, cols and a double *data where element (i, j) is data[i*cols + j]. Every operation returns a new Matrix; a data == NULL result signals an error. mat_inverse augments A with the identity and reduces it to [I | A⁻¹]. The multiply loop uses i-k-j order for cache efficiency.
Folder structure
Complete source code
Makefile
What each file does
- src/matrix.h
- The
Matrixtype and the API. - src/matrix.c
- Allocation, element access, add/multiply/transpose, determinant and Gauss–Jordan inverse.
- src/main.c
- Reading matrices and the operations menu; frees every result.
- Makefile
- Build automation:
makebuilds./app,make testruns the sample session and compares it with the expected output,make cleanremoves build files.
How to run it
Build
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
1 2 2 1 2 3 4 2 2 5 6 7 8 2 2 3 1 2 3 4 5 6 3 2 7 8 9 10 11 12 4 3 3 2 -3 1 2 0 -1 1 4 5 5 2 2 4 7 2 6 5 2 2 1 2 2 4 0
Testing
- Diff with
tests/expected-output.txt. - The determinant of [[2,−3,1],[2,0,−1],[1,4,5]] must be 49.
- Inverting a singular matrix (e.g. [[1,2],[2,4]]) must report it as singular.
Common errors
Inverse contains nan
Without pivoting, a zero on the diagonal causes division by zero. Always pivot on the largest absolute value.
Values like -0.0000 appear
Floating-point results near zero can be negative; mat_print prints values below 5e-5 as 0.
Possible improvements
- Solve linear systems Ax = b
- LU decomposition
- Read matrices from files
Additional challenges
- 1Compute the rank of a matrix.
- 2Implement Strassen's multiplication and compare its speed for 256 × 256.
- 3Add an eigenvalue estimate using the power method.
Built and tested it yourself? Mark it to update your dashboard.