3

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

Dimensions[s]

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

rhermans
  • 36,518
  • 4
  • 57
  • 149
Kiril Danilchenko
  • 2,019
  • 1
  • 9
  • 18

1 Answers1

7

"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 SparseArray`SparseArrayDimensions,

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

based on the estimations by @HenrikSchumacher

SparseArray`SparseArrayDimensions[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"] := SparseArray`SparseArrayDimensions[s];
Protect[SparseArray];


Side note:

The FullForm reveals

FullForm[s]

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} *)
rhermans
  • 36,518
  • 4
  • 57
  • 149
  • 3
    @KirilDanilchenko Just a short note: Dimensions[s] does not compute anything. Quite likely, it calls SparseArraySparseArrayDimensionsand 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