Get the dimensions from the SparseArray properties

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}]


I can calculate the s dimension by

Dimensions[s]


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

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

"Properties"

The listed "Properties" does not include dimensions

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


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

Dimensions works, as you stated,

Dimensions[s]
(* {3, 3} *)


And there is also SparseArraySparseArrayDimensions,

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

based on the estimations by @HenrikSchumacher

SparseArraySparseArrayDimensions[s]
(* {3, 3} *)


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

Unprotect[SparseArray];
(s_SparseArray)["Dimensions"] := SparseArraySparseArrayDimensions[s];
Protect[SparseArray];


Side note:

The FullForm reveals

FullForm[s]


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

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

spart[s, 2]
(* {3, 3} *)

• @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. – Henrik Schumacher Jul 29 '18 at 13:34