CSR matrix

CSR matrices use three one-dimensional arrays to represent a matrix. The CSR format uses these three arrays:

  • A: Values present within the array.
  • IA: The index in which each of these values is present. These are defined as follows:
    • The value of IA at the 0 index, IA[0] = 0
    • The value of IA at the i index, IA[i] = IA[i − 1] + (number of non-zero elements on the i-1th row in the original matrix)
  • JA: Stores the column indices of the elements.

The following image shows an example of a 4 x 4 matrix. This is the matrix that we are going to use in our following code sample:

We can calculate these values as follows:

  • A = [ 1 2 3 4]
  • IA = [0 1 2 3 4]
  • JA = [2 0 3 1]

We can validate this using the sparse package, as shown in the following code snippet:

package main

import (
"fmt"
"github.com/james-bowman/sparse"
"gonum.org/v1/gonum/mat"
)

func main() {
sparseMatrix := sparse.NewDOK(4, 4)
sparseMatrix.Set(0, 2, 1)
sparseMatrix.Set(1, 0, 2)
sparseMatrix.Set(2, 3, 3)
sparseMatrix.Set(3, 1, 4)
fmt.Print("DOK Matrix: ", mat.Formatted(sparseMatrix), " ") // Dictionary of Keys
fmt.Print("CSR Matrix: ", sparseMatrix.ToCSR(), " ") // Print CSR version of the matrix
}

The result shows us the reconverted values of the DOK representation of the matrix that we created, as well as its corresponding CSR matrix:

The output from this code shows us a CSR matrix that prints the IA, JA, and A values, respectively. As the matrix grows, being able to calculate a CSR matrix makes matrix manipulation more and more efficient. Computer science often manipulates matrices with millions of rows and columns, so being able to do so in an efficient manner makes your code much more performant.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.148.210