Content  


Example 4: Sparse Matrices

There are two different sparse matrix types provided by ViennaCL, compressed_matrix and coordinate_matrix. In the current release of ViennaCL, the use of compressed_matrix is encouraged over coordinate_matrix, since compute kernels for the latter require additional optimizations.


compressed_matrix<T, A> represents a sparse matrix using a compressed sparse row scheme. T is the floating point type. A is the alignment and defaults to 1 at present.

The second type, coordinate_matrix<T, A>, represents a sparse matrix where entries are stored as triplets (i,j,val), where i is the row index, j is the column index and val is the entry. Again, T is the floating point type. A is the alignment and defaults to 128 at present.

In general, sparse matrices should be set up on the CPU and then be pushed to the compute device using copy(), because the management of map based sparse matrices is inefficient on most compute devices such as GPUs.

Handling sparse matrices in ViennaCL
typedef float        ScalarType;
//typedef double    ScalarType; //use this if your GPU supports double precision
 
// Set up a few ViennaCL objects:
viennacl::compressed_matrix<ScalarType> vcl_compressed_matrix;
viennacl::coordinate_matrix<ScalarType> vcl_coordinate_matrix;
viennacl::vector<ScalarType> vcl_rhs; 
viennacl::vector<ScalarType> vcl_result;
 
/* set up right hand side vector vcl_rhs as in the other examples */
 
// copy data from a sparse matrix on the CPU to the GPU:
copy(cpu_sparse_matrix, vcl_compressed_matrix);
copy(cpu_sparse_matrix, vcl_coordinate_matrix);
 
// ViennaCL only allows to compute matrix-vector products for sparse matrix types:
vcl_result = viennacl::linalg::prod(vcl_compressed_matrix, vcl_rhs);
vcl_result = viennacl::linalg::prod(vcl_coordinate_matrix,  vcl_rhs);