3
$\begingroup$

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

$\endgroup$
  • $\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
6
$\begingroup$

"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} *)
$\endgroup$
  • 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.