CVS MatrixScalarProduct
My current study is to add more features/methods for the compressed value storage (CVS) format. CVS is a lossless compression format for sparse matrices. A lot of things are easier with CVS than CRS/CCS. Let's look at MatrixScalarProduct() and MatrixScalarProductInPlace().
Matrix-scalar multiplication simply multiplies all elements in the matrix to a scalar value. Programmatically, the operation focuses on looping through the CVS.Value collection, multiplying each item to the scalar value.
CVSExtensions adds two versions of matrix-scalar multiplication: MatrixScalarProduct() returns the result in a new CVS instance. MatrixScalarProductInPlace() stores the result in the same CVS instance.
Matrix-scalar multiplication simply multiplies all elements in the matrix to a scalar value. Programmatically, the operation focuses on looping through the CVS.Value collection, multiplying each item to the scalar value.
CVSExtensions adds two versions of matrix-scalar multiplication: MatrixScalarProduct() returns the result in a new CVS instance. MatrixScalarProductInPlace() stores the result in the same CVS instance.
public static CVS<P> MatrixScalarProduct<T, S, P>(this CVS<T> cvs,
S scalar)
{
(List<T> value,
List<List<int>> linearIndex,
MatrixLinearIndexMode linearIndexMode,
(int rows, int columns) size) = cvs;
List<P> newValue = new List<P>();
List<List<int>> newLinearIndex = new List<List<int>>();
if (!scalar.Equals(default(S)))
{
for (int i = 0; i < value.Count; i++)
{
newValue.Add(value[i] * (dynamic)scalar);
newLinearIndex.Add(new List<int>(linearIndex[i]));
}
}
return new CVS<P>(newValue, newLinearIndex, linearIndexMode, size);
}
public static void MatrixScalarProductInPlace<T>(this CVS<T> cvs,
T scalar)
{
if (scalar.Equals(default(T)))
{
cvs.Value.Clear();
cvs.LinearIndex.Clear();
}
else
{
for (int i = 0; i < cvs.Value.Count; i++)
{
cvs.Value[i] *= (dynamic)scalar;
}
}
}
Matrix-scalar multiplication is quick and easy with CVS. Because there can be fewer NDNZ in CVS compared to NNZ in CRS/CCS, CVS can offer faster performance.
Comments
Post a Comment