Skip to content

Distributed Regridding

Julia Sloan edited this page Jun 29, 2023 · 14 revisions

Sparse Matrix Representation in Julia (SparseMatrixCSC)

A simple example

Consider the following dense matrix:

$$matrix = \begin{bmatrix} 6 & 0 & 7 & 0\\0 & 0 & 1 & 0\\-8 & 3 & 0 & 0\\0 & 0 & 5 & -2 \end{bmatrix}$$

Using Julia's sparse matrix representation, this would be represented as the following collection of integers and vectors:

sparse = SparseMatrixCSC(matrix)

sparse.m: 4

sparse.n: 4

sparse.nzval: [-6 7 1 -8 3 5 -2], with length 7

sparse.rowval: [1 3 3 1 2 4 4] with length 7 (= |sparse.nzval|)

sparse.colptr: [1 3 4 7 8] with length 5 (= sparse.n + 1)

Here, m and n are the number of rows and columns in sparse, respectively.

sparse.nzval is a vector containing the nonzero values of matrix.

sparse.rowval is a vector containing the row indices of the nonzero values of matrix. That is, sparse.rowval[i] gives the row index of the value sparse.nzval[i] in the original dense matrix.

sparse.colptr is a vector containing the indices into sparse.nzval of the first nonzero value in each column of the dense matrix, as well as a final bound which is 1 larger than the largest index of sparse.nzval (i.e. |sparse.nzval| + 1). Values from column j in the original dense matrix will have indices in sparse.nzval in the range [sparse.colptr[j], sparse.colptr[j+1]). Because this vector contains one index for each column of the original matrix and one extra bound value, its length is always n + 1. This is perhaps a less intuitive approach than storing all the column indices into the original dense matrix would be (as is done for rowval), but it encodes sufficient information for the user to be able to recover the dense matrix from the sparse representation, and requires storing fewer numbers than storing all column indices would.

These fields provide all the necessary information to index into a sparse matrix, or to convert a sparse matrix to the corresponding dense matrix.

See also

Julia's SparseMatrixCSC documentation

Clone this wiki locally