Skip to content

Sparse Matrix

axelanglet edited this page May 17, 2017 · 8 revisions

This project is separate in three files, the Sparse Matrix class, the Sparse Matrix reader and the program. This project is used for multiply a sparse matrix by a vector. We use Vector Reader to create some vector.

Sparse Matrix class

SparseMatrix is a class that materialize a matrix, but it doesn't store the null number.
This class have 3 attribut :

  • data: a float array that store all non null numbers.
  • indices: a uint array that store the column number of each element second is the number of element on each line.
  • rows: a uint array that store the number of non null number on each line since the begin of the matrix.

This class have two method:

  • The first is a constructor that create a sparse matrix from a dictionary<uint, float> array .
  • The second is Laplacian_1D(uint rowsCount) that return a laplacian sparse matrix, the parameter is the number of row( it's a square matrix).

Sparse Matrix Reader

This file regroup the method to create a sparse matrix from a .mtx file and it can only create a general, symmetric or skew-symmetric matrix. You can download some .mtx files here.

the important function is ReadMatrixFromFile(string filePath) which return a dictionary<uint, float> array that can be used to create a sparse matrix.

Program

To begin we create a laplacian matrix and a vector with the corresponding size and a vector which receive the product.

  SparseMatrix A = SparseMatrix.Laplacian_1D(10000000);
  float[] X = VectorReader.GetSplatVector(10000000, 1.0F);
  float[] B = new float[A.rows.Length - 1];

Like the first examples, create and initialize a Hybrunner and a wrapper object to compute the code on the device and call the function with the EntryPoint attribute on the host and on the device.

  HybRunner runner = HybRunner.Cuda("SparseMatrix_CUDA.dll").SetDistrib(20, 256);
  dynamic wrapper = runner.Wrap(new Program());

  Multiply(B, A, X, X.Length);
  wrapper.Multiply(B, A, X, X.Length);

This is the function that compute the multiplication between the sparse matrix and the vector.

  [EntryPoint]
  public static void Multiply(float[] res, SparseMatrix m, float[] v, int N)
  {
      Parallel.For(0, N, (i) =>
      {
          uint rowless = m.rows[i];
          uint rowup = m.rows[i + 1];
          float tmp = 0.0F;
          for (uint j = rowless; j < rowup; ++j)
          {
              tmp += v[m.indices[j]] * m.data[j];
          }
          res[i] = tmp;
      });
  }

Shared Matrix Home Conjugate Gradient
Clone this wiki locally