In the sparse matrix, we have a list of properties: specified elements, dimension, default, and density. I am interested in getting this data without calculating them again. For an example, the following sparse matrix has dimension 3*3

s = SparseArray[{{1, 1} -> 1, {2, 2} -> 2, {3, 3} -> 3, {1, 3} -> 4}]

enter image description here

I can calculate the s dimension by


but I look for option to get this information from s properties

  • $\begingroup$ ok, fair enough $\endgroup$ – Kiril Danilchenko Jul 29 '18 at 10:44
  • 1
    $\begingroup$ I have asked a new question $\endgroup$ – Kiril Danilchenko Jul 29 '18 at 11:10


The listed "Properties" does not include dimensions

(* {"AdjacencyLists", "Background", "ColumnIndices", "Density", \
"MatrixColumns", "NonzeroValues", "PatternArray", "Properties", \
"RowPointers"} *)

You can read more about SparseArray "Properties" in this answer.

Dimensions works, as you stated,

(* {3, 3} *)

And there is also SparseArray`SparseArrayDimensions,

twice as fast as Dimension, probably alone due to the redirect

based on the estimations by @HenrikSchumacher

(* {3, 3} *)

Following the lead from @JasonB. in his answer to a similar question, one could define the desired effect by

(s_SparseArray)["Dimensions"] := SparseArray`SparseArrayDimensions[s];

Side note:

The FullForm reveals


Mathematica graphics

Where the second element is the dimensions, and from the documentation under Possible Issues you can find

Mathematica graphics

HoldPattern[spart[SparseArray[stuff___], p_]] := {stuff}[[p]]

spart[s, 2]
(* {3, 3} *)
  • 3
    $\begingroup$ @KirilDanilchenko Just a short note: Dimensions[s] does not compute anything. Quite likely, it calls SparseArraySparseArrayDimensions` and that one just reads some values from the internal structure of a sparse array. A bit to my surprise, SparseArraySparseArrayDimensions` is twice as fast as Dimension, probably alone due to the redirect I mentioned. It does not matter though, as the timings are of order 3. 10^-7, hence neglectible for nearly all purposes. $\endgroup$ – Henrik Schumacher Jul 29 '18 at 13:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.