Preallocate sparse matrix with max nonzeros in R -
i'm looking preallocate sparse matrix in r (using simple_triplet_matrix) providing dimensions of matrix, m x n, , number of non-zero elements expect have. matlab has function "spalloc" (see below), have not been able find equivalent in r. suggestions?
s = spalloc(m,n,nzmax) creates 0 sparse matrix s of size m-by-n room hold nzmax nonzeros.
whereas may make sense preallocate traditional dense matrix in r (in same way more efficient preallocate regular (atomic) vector rather increasing size 1 one, i'm pretty sure not pay preallocate sparse matrices in r, in situations. why? dense matrices, allocate , assign "piece piece", e.g., m[i,j] <- value
sparse matrices, different: if s[i,j] <- value internal code has check if [i,j] existing entry (typically non-zero) or not. if is, can change value, otherwise, 1 way or other, triplet (i,j, value)
needs stored and means extending current structure etc. if piece piece, inefficient... irrespectively if had done preallocation or not.
if, on other hand, know in advance [i,j]
combinations contain non-zeroes, "pre-allocate", in case, store vector i
, j
of length nnzero
, say. , use underlying "algorithm" construct vector x
of same length contains corresponding value
s, i.e., entries. now, indeed, @pafnucy suggested, use spmatrix()
or sparsematrix()
, 2 different versions of same functionality: constructing sparse matrix, given contents.
i happy further, maintainer of matrix
package.
Comments
Post a Comment