MODULE 2.2: SPARSE MATRICES, TRIPLET REPRESENTATION & SPECIAL MATRICES

Learn how sparse matrices save memory when most entries are zero, how triplet (3-tuple) and compressed formats store non-zero values, and how special structured matrices work.

πŸ’‘ Summary: Recording Only Filled Seats Instead of Empty Rows

Suppose a 1,000 Γ— 1,000 grid has 1,000,000 cells, but 99% of them are 0 (empty or inactive). Storing every single zero in a full 2D array wastes huge memory and slows down scans. A sparse matrix focuses on storing only the meaningful non-zero entries along with their coordinates.

In triplet (3-tuple) representation, each non-zero entry is recorded as (row, column, value), while header metadata records total rows, total columns, and non-zero count. Meanwhile, special matrices (diagonal, upper/lower triangular, symmetric, tridiagonal) follow predictable patterns so only key elements need explicit storage.

1. Sparse Matrices & Triplet (3-Tuple) Representation
A matrix is generally considered sparse when a large proportion of its elements are zero (often more than half or most entries, depending on context):
  • Triplet List Format: Row 0 stores (total_rows, total_cols, non_zero_count), followed by one (r, c, val) tuple per non-zero element.
  • Memory Trade-Off: Triplet storage uses $3 \times (k + 1)$ entries (where $k$ is non-zero count), which saves space when $3(k + 1) < R \times C$, but costs more if the matrix is mostly non-zero.
  • Coordinate Lookups vs. Scans: Compact representations excel at iterating non-zero entries, though random cell access can take longer than direct 2D indexing.
Representation Storage Pattern Best When
Full 2D Array Stores all $R \times C$ cells including zeros Matrix is dense and random $(r, c)$ access is frequent
Triplet (3-Tuple) Stores (row, col, value) for non-zero items Matrix is large and mostly zeros ($3(k+1) \ll R \times C$)
Python (sparse_triplet.py)
def to_triplet(matrix):
    rows = len(matrix)
    cols = len(matrix[0]) if rows > 0 else 0
    triplets = []
    for r in range(rows):
        for c in range(cols):
            if matrix[r][c] != 0:
                triplets.append((r, c, matrix[r][c]))
    header = (rows, cols, len(triplets))
    return [header] + triplets

grid = [
    [0, 0, 15, 0],
    [0, 0, 0, 0],
    [22, 0, 0, 8],
    [0, 0, 0, 0]
]

triplet_table = to_triplet(grid)
print("Header (rows, cols, nnz):", triplet_table[0])
print("Non-zero triplets (r, c, val):", triplet_table[1:])
print(f"Dense cells: {16} | Triplet rows: {len(triplet_table)}")
Output: Header (rows, cols, nnz): (4, 4, 3) Non-zero triplets (r, c, val): [(0, 2, 15), (2, 0, 22), (2, 3, 8)] Dense cells: 16 | Triplet rows: 4
2. Special Structured Matrices
Certain square or banded matrices have regular zero/non-zero patterns that let us compress storage cleanly:
  • Diagonal Matrix: Non-zero entries appear only where $i = j$; only $n$ diagonal values are needed for an $n \times n$ matrix.
  • Upper & Lower Triangular Matrices: Entries below ($i > j$) or above ($i < j$) the main diagonal are zero, reducing non-zero storage to $\frac{n(n+1)}{2}$.
  • Symmetric Matrix: $M[i][j] = M[j][i]$ for all $i, j$, so storing only the lower or upper triangle avoids duplicating half the entries.
  • Tridiagonal Matrix: Non-zeros lie only on the main diagonal ($i = j$), superdiagonal ($j = i + 1$), and subdiagonal ($i = j + 1$), needing at most $3n - 2$ entries.
C++ (special_diagonal_matrix.cpp)
#include 
#include 
using namespace std;

// Compact diagonal matrix storing only n diagonal entries instead of n*n
class DiagonalMatrix {
    int n;
    vector diag;
public:
    DiagonalMatrix(int size) : n(size), diag(size, 0) {}

    void set(int i, int j, int val) {
        if (i == j && i >= 0 && i < n) {
            diag[i] = val;
        }
    }

    int get(int i, int j) const {
        if (i < 0 || i >= n || j < 0 || j >= n) return 0;
        return (i == j) ? diag[i] : 0;
    }
};

int main() {
    DiagonalMatrix dm(4);
    dm.set(0, 0, 5);
    dm.set(1, 1, 10);
    dm.set(2, 2, 15);
    dm.set(3, 3, 20);

    cout << "Element (2, 2): " << dm.get(2, 2) << "\n";
    cout << "Element (2, 1): " << dm.get(2, 1) << "\n";
    return 0;
}
Output: Element (2, 2): 15 Element (2, 1): 0
3. 10 Real-Time Examples (Part 1: Examples 1 to 5)
Five real-time systems rely on sparse or structured matrix representations:
  • 1. User-Item Ratings / Interaction Matrix: Most users rate only a tiny fraction of millions of items, making sparse storage essential.
  • 2. Word-Document Term Matrix in Search/NLP: Each document uses only a small subset of a huge vocabulary, leaving most matrix cells zero.
  • 3. Social Network Adjacency Matrix: A person connects to hundreds of accounts out of millionsβ€”most pairs have no direct edge.
  • 4. Warehouse / Store Stock Grid Across Locations: Most products are stocked in select branches rather than every aisle and bin simultaneously.
  • 5. City & Highway Route Connectivity Grid: Direct roads link specific pairs of intersections, so direct-connection matrices are naturally sparse.
Python (realtime_sparse_1_to_5.py)
# 1. Sparse user-item ratings as triplets: (user_idx, item_idx, rating)
ratings_triplets = [
    (0, 12, 5),
    (1, 12, 4),
    (4, 98, 5),
]
print("1. Recorded ratings count:", len(ratings_triplets))

# 3. Sparse adjacency list/triplets for direct road/friend links
edges_triplets = [
    (0, 2, 1),
    (2, 5, 1),
]
print("3. Active direct links:", edges_triplets)
Output: 1. Recorded ratings count: 3 3. Active direct links: [(0, 2, 1), (2, 5, 1)]
4. 10 Real-Time Examples (Part 2: Examples 6 to 10)
Five more real-time examples show sparse and special matrices in simulations, graphs, and engineering:
  • 6. Sensor Grid Where Most Sensors Are Idle: In wide environmental/industrial grids, only active or triggered sensors emit non-zero readings.
  • 7. Class Attendance / Event Check-In Matrix: Across many dates and members, recorded check-ins are a sparse subset of all possible pairs.
  • 8. Pairwise Distance Table Between Locations (Symmetric Matrix): Distance from City A to City B equals distance from City B to City A.
  • 9. Dependency / Prerequisite DAG Matrix (Triangular Structure): Ordering tasks along a topological order naturally yields a triangular structure.
  • 10. 1D Finite-Difference / Nearest-Neighbor Coupling (Tridiagonal Matrix): Each point interacts mainly with its immediate left and right neighbors.
Python (realtime_sparse_6_to_10.py)
# 8. Symmetric distance matrix stored via upper/lower triangle lookup
dist_upper = {
    (0, 1): 12,
    (0, 2): 25,
    (1, 2): 18,
}

def get_distance(a, b):
    if a == b:
        return 0
    key = (min(a, b), max(a, b))
    return dist_upper.get(key, -1)

print("8. Distance (2, 0) via symmetry:", get_distance(2, 0))
print("8. Distance (1, 2):", get_distance(1, 2))
Output: 8. Distance (2, 0) via symmetry: 25 8. Distance (1, 2): 18
5. Exam & Engineering Summary
Keep these practical points in mind for semester exams, lab implementations, and system design:
  • Check sparsity before compressing: If a matrix has many non-zero entries, triplet overhead can exceed a standard 2D array.
  • Know the triplet header: Always record (rows, cols, num_nonzero) so the original matrix dimensions are never lost.
  • Exploit symmetry and band structure: Special matrices cut memory and loop iterations cleanly when mathematical structure is guaranteed.
Python (sparse_summary_check.py)
def should_use_triplet(rows, cols, nonzero_count):
    dense_slots = rows * cols
    triplet_slots = 3 * (nonzero_count + 1)
    return triplet_slots < dense_slots

print("100x100 with 20 non-zeros -> use triplet?", should_use_triplet(100, 100, 20))
print("3x3 with 8 non-zeros -> use triplet?", should_use_triplet(3, 3, 8))
Output: 100x100 with 20 non-zeros -> use triplet? True 3x3 with 8 non-zeros -> use triplet? False