spMatrix               package:Matrix               R Documentation

_S_p_a_r_s_e _M_a_t_r_i_x _C_o_n_s_t_r_u_c_t_o_r _F_r_o_m _T_r_i_p_l_e_t

_D_e_s_c_r_i_p_t_i_o_n:

     User friendly construction of a sparse matrix (inheriting from
     class 'TsparseMatrix') from the triplet representation.

_U_s_a_g_e:

     spMatrix(nrow, ncol, i = integer(), j = integer(), x = numeric())

_A_r_g_u_m_e_n_t_s:

nrow, ncol: integers specifying the desired number of rows and columns.

     i,j: integer vectors of the same length specifying the locations
          of the non-zero (or non-'TRUE') entries of the matrix.

       x: atomic vector of the same length as 'i' and 'j', specifying
          the values of the non-zero entries.

_V_a_l_u_e:

     A sparse matrix in triplet form, as an R object inheriting from
     both 'TsparseMatrix' and 'generalMatrix'.

     The matrix M will have 'M[i[k], j[k]] == x[k]', for k = 1,2,...,
     n, where 'n = length(i)' and 'M[ i', j' ] == 0' for all other
     pairs (i',j').

_S_e_e _A_l_s_o:

     'Matrix(*, sparse=TRUE)' for the more usual constructor of such
     matrices; similarly, 'sparseMatrix' which is a bit more general
     than 'spMatrix()' and returns a 'CsparseMatrix' which is often
     slightly more desirable.   Further, 'bdiag' and 'Diagonal' for
     (block-)diagonal matrix constructors.

     Consider 'TsparseMatrix' and similar class definition help files.

_E_x_a_m_p_l_e_s:

     ## simple example
     A <- spMatrix(10,20, i = c(1,3:8),
                          j = c(2,9,6:10),
                          x = 7 * (1:7))
     A # a "dgTMatrix"
     summary(A)
     str(A) # note that *internally* 0-based indices (i,j) are used

     L <- spMatrix(9, 30, i = rep(1:9, 3), 1:27,
                   (1:27) %% 4 != 1)
     L # an "lgTMatrix"

     ### This is a useful utility, to be used for experiments :

      rSpMatrix <- function(nrow, ncol, nnz,
                            rand.x = function(n) round(rnorm(nnz), 2))
      {
          ## Purpose: random sparse matrix
          ## --------------------------------------------------------------
          ## Arguments: (nrow,ncol): dimension
          ##          nnz  :  number of non-zero entries
          ##         rand.x:  random number generator for 'x' slot
          ## --------------------------------------------------------------
          ## Author: Martin Maechler, Date: 14.-16. May 2007
          stopifnot((nnz <- as.integer(nnz)) >= 0,
                    nrow >= 0, ncol >= 0,
                    nnz <= nrow * ncol)
          spMatrix(nrow, ncol,
                   i = sample(nrow, nnz, replace = TRUE),
                   j = sample(ncol, nnz, replace = TRUE),
                   x = rand.x(nnz))
      }

      M1 <- rSpMatrix(100000, 20, nnz = 200)
      summary(M1)

