Skip to content

SparseArray ​

A dense array built from position → value rules.

✓ checked against that system · ! checked, with disagreements (hover a chip)Wolfram LanguageSparseArray!
SparseArray(rules)a dense array whose dimensions are the largest index seen on each axis, elsewhere 0.
SparseArray(rules, dims)like the 1-argument form, with the dimensions given explicitly.
SparseArray(rules, dims, default)like the 2-argument form, with positions not covered by rules filled with default instead of 0.
Typed signatures
TypePackageApplies
(any, any?, any?) -> collectioncombinatoricsalways

Domain: Collections

Details
  • A dense list (no rules) is its own dense form: SparseArray({1, 2, 3}) is {1, 2, 3}.
  • Each rule is pos→valuepos \to value: pospos is a plain integer for a vector, or a list of integers for a matrix or higher-rank array.
  • No distinct sparse storage type is kept — the result densifies immediately into an ordinary nested list, so Normal of it is unchanged, and it is not practical for arrays too large to materialise.

Examples

Basic #
live ↗
InSparseArray([Rule(1,x),Rule(3,y)],4)\mathrm{SparseArray}(\bigl\lbrack\mathrm{Rule}(1, x), \mathrm{Rule}(3, y)\bigr\rbrack, 4)Out[x,0,y,0]\bigl\lbrack x, 0, y, 0\bigr\rbrack
Scope #

With no dims given, they're the largest index seen per axis

live ↗
InSparseArray([Rule([1,1],5),Rule([2,2],7)])\mathrm{SparseArray}(\bigl\lbrack\mathrm{Rule}(\bigl\lbrack1, 1\bigr\rbrack, 5), \mathrm{Rule}(\bigl\lbrack2, 2\bigr\rbrack, 7)\bigr\rbrack)Out[[5,0],[0,7]]\bigl\lbrack\bigl\lbrack5, 0\bigr\rbrack, \bigl\lbrack0, 7\bigr\rbrack\bigr\rbrack

A third argument fills the gaps instead of 0

live ↗
InSparseArray([Rule(2,9)],3,−1)\mathrm{SparseArray}(\bigl\lbrack\mathrm{Rule}(2, 9)\bigr\rbrack, 3, -1)Out[−1,9,−1]\bigl\lbrack-1, 9, -1\bigr\rbrack
live ↗
InSparseArray([[1,0,0],[1,2,0],[1,2,3]])\mathrm{SparseArray}(\bigl\lbrack\bigl\lbrack1, 0, 0\bigr\rbrack, \bigl\lbrack1, 2, 0\bigr\rbrack, \bigl\lbrack1, 2, 3\bigr\rbrack\bigr\rbrack)Out[[1,0,0],[1,2,0],[1,2,3]]\bigl\lbrack\bigl\lbrack1, 0, 0\bigr\rbrack, \bigl\lbrack1, 2, 0\bigr\rbrack, \bigl\lbrack1, 2, 3\bigr\rbrack\bigr\rbrack
Possible issues #

Normal is a no-op here — SparseArray already returns a plain dense list

live ↗
InNormal⁡(SparseArray([Rule(1,a)],2))\operatorname{Normal}(\mathrm{SparseArray}(\bigl\lbrack\mathrm{Rule}(1, a)\bigr\rbrack, 2))Out[a,0]\bigl\lbrack a, 0\bigr\rbrack
About
Examples5
Checked againstWolfram Language 2 agree3 differ
CrosswalkWolfram Language