Convert triplets to sparse format.
A sparse matrix can also be presented as pairs of the three elements called triplets. For each non zero value in the matrix we specify it's position: Row, Column, and it's Value. MatrixSize defines the size of the matrix and sets the Size and Cols properties. The value of the Rows property is set to match the Cols property. The maximum row and column index may not exceed MatrixSize-1. This is usually the most efficient way to convert a given dense matrix to sparse format. The values do not need to be ordered, the same coordinates can appear more than once. All values having the same coordinates will be summed together. This routine can therefore also be used as a way to sum multiple sparse matrices. Triplets can be represented by three arrays: Row, Column and Values or they can all be stored in one TMtx matrix.
Example 1
Test sparseToTriplets, TripletsToSparse methods.
var R1,C1: TIntArray;
V1: TSampleArray;
SparseA, SparseB: TSparseMtx;
A: Matrix;
begin
SparseA := TSparseMtx.Create;
SparseB := TSparseMtx.Create;
try
// setup sparse , rows, cols, non-zero elements
SetLength(R1,SparseA.NonZeros);
SetLength(C1,SparseA.NonZeros);
SetLength(V1,SparseA.NonZeros);
SparseA.SparseToTriplets(R1,C1,V1);
SparseB.TripletsToSparse(SparseA.Cols,SparseA.Cols,R1,C1,V1);
SparseA.SparseToDense(A);
if not SparseB.Equal(SparseA,1E-5) then ERaise('Not equal');
if not SparseA.Equal(A,0,True) then ERaise('Not equal');
SparseA.SparseToTriplets(A);
SparseB.TripletsToSparse(SparseA.Cols,SparseA.Cols,A);
if not SparseA.Equal(SparseB) then ERaise('Not equal');
finally
SparseA.Destroy;
SparseB.Destroy;
end;
end;
using Dew.Math;
using Dew.Math.Units;
namespace Dew.Examples
{
private void Example()
{
Matrix A = new Matrix(0,0);
TSparseMtx SparseA = new TSparseMtx();
TSparseMtx SparseB = new TSparseMtx();
int[] R1 = new int[SparseA.NonZeros];
int[] C1 = new int[SparseA.NonZeros];
double[] V1 = new double[SparseA.NonZeros];
SparseA.SparseToTriplets(ref R1,ref C1,ref V1);
SparseB.TripletsToSparse(SparseA.Cols,SparseA.Cols,R1,C1,V1,0.0);
SparseA.SparseToDense(A);
if (!SparseB.Equal(SparseA,1E-5)) throw("Not equal");
if (!SparseA.Equal(A,0,true)) throw("Not equal");
SparseA->SparseToTriplets(A);
SparseB.>TripletsToSparse(SparseA.Cols,SparseA.Cols,A,0.0);
if (!SparseA.Equal(SparseB)) throw("Not equal");
}
}
Declaration
Procedure TripletsToSparse(RowCount, ColCount: integer; const Row, Column: TIntegerArray; const aCValues: TCplxArray; Threshold: TSample = 0);
Description
Complex version of TripletsToSparse. An exception is raised if calling sparse matrix is not complex.
Declaration
Procedure TripletsToSparse(RowCount, ColCount: integer; Triplets: TMtx);
Description
The triplets are stored in the Triplets matrix. First row are row indices, second row are column indices and the third row stores the values. If the matrix is complex, the row and column indicies are stored in the real part of the complex values.