## Sparse Vectors | Extreme Optimization Numerical Libraries for .NET Professional |

Sparse vectors are represented by the
SparseVector

The SparseVector

The example below constructs three sparse vectors, each with one million elements. The second and third vectors have an initial capacity of 100 nonzero values:

var v1 = Vector.CreateSparse<double>(1000000); var v2 = Vector.CreateSparse<double>(1000000, 1e-4); var v3 = Vector.CreateSparse<double>(1000000, 100);

The fourth and final overload takes three arguments. The first is once again the length. The second argument is an integer array containing the indexes of the nonzero elements of the vector. The third argument is a Double array containing the corresponding values. The lengths of the arrays must be equal, and all indexes must be within the proper range. If the same index occurs multiple times, then the corresponding element equals the sum of the all the values with that index.

The next example constructs a new sparse vector of length one million, with non-zeros
at index 10^{k} for k in the range 0 to 5:

int[] indexes = { 1, 10, 100, 1000, 10000 }; double[] values = { 1.0, 10.0, 100.0, 1000.0, 10000.0 }; var v4 = Vector.CreateSparse(1000000, indexes, values);

Elements of sparse vectors can be accessed in the same way as for any other vector. If an element is set to a nonzero value, the element is automatically added to the list of nonzero elements. If the vector was at full capacity, then the capacity is automatically extended.

It is possible to iterate over the nonzero elements of a sparse vector efficiently.
The NonzeroElements
property returns a sequence of
IndexValuePair

The code below uses the NonzeroElements property to list the nonzero elements of the vector v4:

foreach (var pair in v4.NonzeroElements) Console.WriteLine("Element {0} = {1}", pair.Index, pair.Value);

All properties and methods of vectors are also available for sparse vectors. Nearly all of these methods have optimized sparse implementations. This includes norms, most arithmetic operations including addition, subtraction, scaling and matrix products. For example:

Note that some operations on sparse vectors result in a dense vector, causing memory to be allocated for all elements. For example, the result of adding a scalar to a sparse vector is dense.

Copyright Â© 2004-2021,
Extreme Optimization. All rights reserved.

*Extreme Optimization,* *Complexity made simple*, *M#*, and *M
Sharp* are trademarks of ExoAnalytics Inc.

*Microsoft*, *Visual C#, Visual Basic, Visual Studio*, *Visual
Studio.NET*, and the *Optimized for Visual Studio* logo

are
registered trademarks of Microsoft Corporation.