SparseArray

SparseArray[{pos1val1,pos2val2,}]

yields a sparse array in which values vali appear at positions posi.

SparseArray[{pos1,pos2,}{val1,val2,}]

yields the same sparse array.

SparseArray[list]

yields a sparse array version of list.

SparseArray[data,{d1,d2,}]

yields a sparse array representing a d1×d2× array.

SparseArray[data,dims,val]

yields a sparse array in which unspecified elements are taken to have value val.

Details

  • By default, SparseArray takes unspecified elements to be 0.
  • SparseArray[data,] is always converted to an optimized standard form with structure SparseArray[Automatic,dims,val,].
  • Normal[SparseArray[]] gives the ordinary array corresponding to a sparse array object.
  • ArrayRules[SparseArray[]] gives the list of rules {pos1->val1,pos2->val2,}.
  • The elements in SparseArray need not be numeric.
  • The position specifications posi can contain patterns.
  • SparseArray[{{i_,i_}->1},{d,d}] gives a d×d identity matrix.
  • Rules of the form Band[]->vals specify values on bands in the sparse array.
  • With rules posi:>vali the vali are evaluated separately for each set of indices that match posi.
  • SparseArray[list] requires that list be a full array, with all parts at a particular level being lists of the same length.
  • The individual elements of a sparse array cannot themselves be lists.
  • SparseArray[rules] yields a sparse array with dimensions exactly large enough to include elements whose positions have been explicitly specified.
  • SparseArray[rules,Automatic,val] takes unspecified elements to have value val.
  • List and matrix operations are typically set up to work as they do on Normal[SparseArray[]].
  • Functions with attribute Listable are automatically threaded over the individual elements of the ordinary arrays represented by SparseArray objects.
  • Part extracts specified parts of the array represented by a SparseArray object, rather than parts of the SparseArray expression itself.
  • Functions like Map are automatically applied to components in a SparseArray object.
  • SparseArray is treated as a raw object by functions like AtomQ and for purposes of pattern matching.
  • Dimensions gives the dimensions of a sparse array.
  • The standard output format for a sparse array indicates the number of nondefault elements and the total dimensions.

Examples

open allclose all

Basic Examples  (1)

Construct a sparse matrix with values at only a few specified positions:

In[1]:=
Click for copyable input
Out[1]=

View it as a matrix:

In[2]:=
Click for copyable input
Out[2]//MatrixForm=

Convert it to an ordinary dense matrix:

In[3]:=
Click for copyable input
Out[3]=

Scope  (7)

Generalizations & Extensions  (2)

Applications  (4)

Properties & Relations  (3)

Possible Issues  (6)

Neat Examples  (1)

See Also

ArrayRules  Normal  Band  CoefficientArrays  ArrayPlot  Array  ConstantArray  Association

Tutorials

Introduced in 2003
(5.0)
| Updated in 2007
(6.0)