Skip to contents

This helper function allows the extraction of a sparse matrix from a matrix using a similar approach to that implemented in rstan::extract_sparse_parts() and returns these elements in a named list for use in stan. This function is used in the construction of the expectation model (see enw_expectation()).

Usage

extract_sparse_matrix(mat, prefix = "")

Arguments

mat

A matrix to extract the sparse matrix from.

prefix

A character string to prefix the names of the returned list.

Value

A list representing the sparse matrix, containing:

  • nw: Count of non-zero elements in mat.

  • w: Vector of non-zero elements in mat. Equivalent to the numeric values from mat excluding zeros.

  • nv: Length of v.

  • v: Vector of row indices corresponding to each non-zero element in w. Indicates the row location in mat for each non-zero value.

  • nu: Length of u.

  • u: Vector indicating the starting indices in w for non-zero elements of each row in mat. Helps identify the partition of w into different rows of mat.

Examples

mat <- matrix(1:12, nrow = 4)
mat[2, 2] <- 0
mat[3, 1] <- 0
extract_sparse_matrix(mat)
#> $nw
#> [1] 10
#> 
#> $w
#>  [1]  1  5  9  2 10  7 11  4  8 12
#> 
#> $nv
#> [1] 10
#> 
#> $v
#>  [1] 1 2 3 1 3 2 3 1 2 3
#> 
#> $nu
#> [1] 5
#> 
#> $u
#> [1]  1  4  6  8 11
#>