Lesson 10 +30 XP

Sparse Matrix Representation & Arithmetic

Sparse Matrix Representation & Arithmetic

A Sparse Matrix is a matrix in which the majority of elements are zero (zeros / total > 0.5). Storing all zeros in a 2D array wastes O(m × n) memory and causes redundant zero operations.

Sparse Matrix Triplet RepresentationSparse Matrix Triplet Representation

1. Triplet (3-Tuple) Array Representation

Store only non-zero entries as (row, col, val), using index 0 as a metadata header (numRows, numCols, numNonZero):

C
typedef struct {
    int row;
    int col;
    int val;
} Term;
  • Space Savings: 3(t + 1) integers instead of m × n, beneficial whenever 3(t + 1) < m · n.

2. Linked List Representations

  1. Singly Linked List: Each node stores (row, col, val, next) in row-major order.
  2. Orthogonal Header Linked List: Maintains a circular header node for each row and column; each non-zero node stores (row, col, val, right, down) - enabling fast row and column traversals without scanning the whole matrix.

3. Sparse Matrix Transpose (Simple vs Fast)

  • Simple Transpose: For each column c = 0 … cols-1, scan all t terms and emit matching entries with (col, row, val) - O(cols · t).
  • Fast Transpose (O(cols + t)):
  1. Count non-zero entries per column into rowTerms[c].
  2. Compute prefix sums: startingPos[c] = startingPos[c - 1] + rowTerms[c - 1] (starting at 1).
  3. Place each term directly at b[startingPos[a[i].col]++].

4. Sparse Matrix Arithmetic (Addition, Subtraction, Multiplication)

Assuming A and B are sorted in row-major triplet order:

  1. Addition (A + B): Perform a two-pointer merge in O(tA + tB):
  • If (rA, cA) < (rB, cB): copy A's term, advance i.
  • If (rA, cA) > (rB, cB): copy B's term, advance j.
  • If equal: compute sum = valA + valB; emit term only if sum != 0, advance both.
  • Example: Adding (0,1,5) and (0,1,-5) cancels out (sum == 0), so no entry is emitted!
  1. Subtraction (A - B): Identical two-pointer merge, using valA - valB on matching coordinates and -valB when B has an unmatched term.
  2. Multiplication (A × B):
  • First compute Fast Transpose BT so B's columns become rows.
  • For each row r of A and each row c of BT, walk matching col indices with two pointers and accumulate sum += a[i].val * bt[j].val.
  • Emit (r, c, sum) whenever sum != 0.

Checking Whether a Matrix Is Sparse (C program)

A matrix is called sparse when more than half of its elements are zero (the notes' rule: count of zeros > (rows × cols) / 2).

C
#include <stdio.h>
int main(void) {
    int a[10][10], r, c, i, j, zeros = 0;
    printf("Rows and columns: ");
    scanf("%d %d", &r, &c);
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++) {
            scanf("%d", &a[i][j]);
            if (a[i][j] == 0) zeros++;
        }
    if (zeros > (r * c) / 2)
        printf("Sparse matrix (%d zeros)\n", zeros);
    else
        printf("Not a sparse matrix\n");
    return 0;
}

Fully Worked Numeric Example (3 × 3)

TEXT
      A                B               A + B            A × B
  0  4  0          1  0  0          1  4  0          0 12 24
  2  0  0          0  3  6          2  3  6          2  0  0
  0  0  5          7  0  0          7  0  5         35  0  0

Triplet form - row 0 is the header (rows, cols, non-zeros):

ArowcolvalBrowcolval
hdr333hdr334
10141001
21022113
32253126
4207

Transpose of A - swap row and column of every triple, then sort by the new row: (3,3,3), (0,1,2), (1,0,4), (2,2,5).

A + B - merge the two triplet lists in row-major order; equal (row, col) positions are added: (3,3,7), (0,0,1), (0,1,4), (1,0,2), (1,1,3), (1,2,6), (2,0,7), (2,2,5).

A − B - same merge, subtracting B's values: (0,0,−1), (0,1,4), (1,0,2), (1,1,−3), (1,2,−6), (2,0,−7), (2,2,5).

A × B - each triple (i, k, a) of A is multiplied with every triple (k, j, b) of B whose row equals k, adding a·b into C[i][j]:

  • A(0,1,4) × B row 1 → C(0,1) += 12, C(0,2) += 24
  • A(1,0,2) × B row 0 → C(1,0) += 2
  • A(2,2,5) × B row 2 → C(2,0) += 35

Result: (3,3,4), (0,1,12), (0,2,24), (1,0,2), (2,0,35).

ℹ️ Note

Practice (linked representation): store A and B as lists of nodes (row, col, value, next) and write add(A, B) using the same two-pointer merge on (row, col). The logic is identical to the triplet merge; only &quot;next index&quot; becomes &quot;next pointer&quot;.

🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. What is a Sparse Matrix? Explain its 3-Tuple (Triplet) Array and Orthogonal Linked List representations with an example. (7.5 Marks)
  • Write: Sparsity condition (&gt;50% zeros), 3(t+1) space advantage, header row (rows, cols, nonZero), 4×4 matrix → triplet table diagram, and orthogonal header (right, down) node structure.
  • Q2. Write the algorithm for Fast Transpose and Sparse Matrix Addition/Multiplication. (7.5 Marks)
  • Write: rowTerms[] + startingPos[] prefix-sum steps (O(cols+t)), two-pointer merge for A + B, and BT dot-product method for A × B.