Learn R Programming

qlcMatrix (version 0.9.7)

rSparseMatrix: Construct a random sparse matrix

Description

This convenience function constructs a random sparse matrix of specified size, with specified sparsity. This is mainly useful for testing speed and memory load of sparse matrix manipulations

Usage

rSparseMatrix(nrow, ncol, nnz, 
	rand.x = function(n) round(rnorm(nnz), 2), ...)

Arguments

nrow

number of rows of the resulting matrix.

ncol

number of columns of the resulting matrix.

nnz

number of entries of the resulting matrix.

rand.x

randomization used for the construction of the entries. if NULL then a pattern matrix is constructed (random entries without values).

...

Other arguments passed to sparseMatrix internally.

Value

Returns a sparse matrix of the type dgCMatrix. Defaults to random numeric entries with two decimal digits, generated randomly from a normal distribution with mean = 0 and sd = 1.

When rand.x = NULL then the result is a pattern matrix of type ngCMatrix.

Details

The sparsity of the resulting matrix (i.e. the fraction of non-zero entries to all entries) is \(\frac{nnz}{nrow * ncol}\).

See Also

For random permutation matrices, see pMatrix-class. Specifically note the construction option (p10 <- as(sample(10),"pMatrix")).

Examples

Run this code
# NOT RUN {
# example with reasonably large (100.000 by 100.000) but sparse matrix
# (only one in 10.000 entries is non-zero). On average 10 entries per column.
X <- rSparseMatrix(1e5, 1e5, 1e6)
print(object.size(X), units = "auto")

# speed of cosine similarity
system.time(M <- cosSparse(X))

# reduce memory footprint by removing low values
print(object.size(M), units = "auto")
M <- drop0(M, tol = 0.1)
print(object.size(M), units = "auto")
# }

Run the code above in your browser using DataLab