Convert sparse matrix to triplets.
Complex version. An exeption is raised if calling sparse matrix is not complex.
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. SparseToTriplets will convert the calling sparse matrix data to the triplets format. The data will be sorted first by columns and then by rows. 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.
uses MtxExpr, Sparse, Math387;
procedure Example;
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;
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];
Matrix A = new Matrix(0,0);
sarseA.SparseToTriplets(ref R1,ref C1,ref V1);
sparseB.TripletsToSparse(sparseA.Cols,sparseA.Cols,R1,C1,V1,0.0);
sparseA.SparseToDense(A,10000000);
if (!sparseB.Equal(sparseA,1.0E-5)) throw("Not equal");
if (!sparseA.Equal(A,0,true)) throw("Not equal");
sparseA.SparseToTriplets(A,false);
sparseB.TripletsToSparse(sparseA.Cols,sparseA.Cols,A);
if (!sparseA.Equal(sparseB)) throw("Not equal");
Declaration
Procedure SparseToTriplets(Triplets: TMtx; ImInRow: boolean = False);
Description
Triplets are stored in the first three rows of the matrix. First row stores the row indices, the second stores the column indices and the third row stores the matrix values. In case of a complex matrix and if ImInRow is True, the imaginary part's of the complex numbers are stored in the fourth row.