Storing a Sparse Vector
A sparse vector can store its dimension and only the positions whose values differ from the default zero.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Write a concrete representation
A five-dimensional vector with entries \(0,7,0,0,2\) can store size five and pairs \((1,7)\) and \((4,2)\). Omitting the size makes it ambiguous when trailing zeros matter. Zero-based indexing determines the position of each value.
Choose lookup and traversal rules
A dictionary supports position lookup with default zero for valid absent positions. A sorted list of pairs supports traversal by position. A function contract should still reject positions beyond the declared dimension.[1]
Match indices before multiplying values
For vectors of length six with nonzeros \(x_1=3,\ x_4=-2\) and \(y_1=4,\ y_3=8,\ y_4=5\), only indices one and four contribute to the dot product. The result is \(3\cdot4-2\cdot5=2\). See joining by keys.
Index x y product
1 3 4 12
3 0 8 0
4 -2 5 -10
Total 2
Validate dimensional metadata and repeated indices
Empty storage can represent an all-zero vector of any supported length. The declared length remains essential. A sparse file with repeated coordinates needs a rule to combine or reject them. Test a nonzero at the last valid index. For a dot product, reject unequal declared lengths even when both maps are empty.