# Save a list as a value in the sparse matrix

I am interested in save a list (the size of the list is two) of numbers in the sparse matrix, but this is not supported. Maybe you familiar with some workarounds or any suggestion on another data structure?

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

• is "{2, 3}" (instead of {2, 3}) acceptable? – kglr Aug 2 '18 at 10:24
• .. or FromDigits[{2, 3}, x]? – kglr Aug 2 '18 at 10:30
• I want to do computation after the definition. So saving the data as String may slowing the calculation. – Kiril Danilchenko Aug 2 '18 at 10:59
• how about using a 3D array instead of 2D: rules = {{1, 1} -> {2, 3}, {2, 2} -> 2, {3, 3} -> 3, {1, 3} -> 4};SparseArray[ Flatten[rules /. Rule[a_, b_] :> Thread[(Append[a, #] & /@ Range[Length@If[Head[b] === List, b, {b}]]) -> b]]]? – kglr Aug 2 '18 at 11:04
• I suspect that you want to use SparseArray for something for which it was not made for. If you tell us what you actually want to do, then, maybe, we can tell you how to do it with SparseArray or another suitable data type. – Henrik Schumacher Aug 2 '18 at 18:08

This is a hacky workaround.

X = {{1, 1} -> 2, {1, 1} -> 3, {2, 2} -> 2, {3, 3} -> 3, {1, 3} -> 4}
A = With[{spopt = SystemOptions["SparseArrayOptions"]},
InternalWithLocalSettings[
SetSystemOptions["SparseArrayOptions" -> {"TreatRepeatedEntries" -> List}],
SparseArray[X, {3, 3}, 0],
SetSystemOptions[spopt]
]
];
Normal[A]


{{{2, 3}, 0, 4}, {0, 2, 0}, {0, 0, 3}}

Usually, one uses this with "TreatRepeatedEntries" -> Total for additive assembly. The default value of "TreatRepeatedEntries" is First.

Overall, Mathematica is quite inconsistent with the handling of sparse array entries with head List. Any other (symbolic) head work seems to work without any problems. So if you do not rely on packed arrays as entries, you can also use this:

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

• Thank you @Henrik. I a little bit confused by the following fact when I update the sparse matrix (which I created according to your advice) I get List. A[[1, 3]] = {1, 55};Head@A – Kiril Danilchenko Aug 2 '18 at 12:06
• @KirilDanilchenko That's one of things I meant with "inconsistent". Notice that most routines for (and actually also the data structure of) SparseArray are optimized for matrices with entries only in one of the following data types: Real, Integer, or Complex. Everything beyond that can be considered as luxury, in particular since most other programming languages do not support anything beyond. Have also a look at Association`: It provides more flexibility in many ways, but it is also less performant for several tasks. – Henrik Schumacher Aug 2 '18 at 17:58