sprand

Sparse matrix with random entries uniformly distributed between 0 and 1.

Category: Mathematics > Sparse Matrices

Syntax

R = sprand(m, n, density)

Returns an m-by-n sparse matrix with about density*m*n nonzeros.

R = sprand(S)

Returns a random matrix with the same sparsity pattern as S.

Description

The positions of the nonzeros are chosen at random, so the actual number can be somewhat different from the requested density when two draws land on the same position. Use rng before the call for reproducible matrices.

It is used to build test matrices for sparse algorithms. For normally distributed values use sprandn.

Input arguments

m, n
Size of the matrix.
density
Fraction of entries that are nonzero, from 0 to 1.
S
Sparse matrix whose pattern is copied.

Output arguments

R
Sparse matrix whose nonzeros are drawn from the uniform distribution on (0, 1).

Example

A random sparse matrix

rng(1);
R = sprand(6, 6, 0.3);
size(R)
issparse(R)
all(nonzeros(R) > 0 & nonzeros(R) < 1)
Output
ans = 1×2

     6     6
ans = logical
   1
ans = logical
   1

Notes

The matrices produced for a given seed differ from MATLAB's. MatLivre stores sparse matrices densely, so they save no memory, and sizes above 200 million elements are rejected. Results and display match MATLAB for ordinary sizes.

See also

sprandn sprandsym rand sparse