Mathematica Asked on November 2, 2020
I have a table of lists, ie. s = { {1, 2, 4}, {7, 11}, {3, 4, 12} }
. From this table, I would like to create the table of points { {1,1} , {1,2} , {1,4} , {2,7} , {2,11} , {3,3} , {3, 4} , {3, 12} }
where for each element $k$ of the $i$-th part of s
, the point {i,k}
is contained in the new table.
How can I do this? I am not experienced with Mathematica and only know how to use Table
, Select
, Part
, etc. But those do not seem to work here.
Note: these were only examples; my actual s
is much larger, so doing this manually is right out.
Building up the answer step by step is sometimes useful. Especially if you might alter the procedure later. The pipeline below builds step by step from left to right. (Range@Length@s
is same as Range[Length[s]]
). You have to understand //
and short pure functions to understand the line below.
Riffle[Range@Length@s, s] // Partition[#, 2] & // Map[Thread, #] & //
Flatten[#, 1] &
You can start just the part before the first // and then add steps sequentially to understand what is going on. That's how I developed it---from left to right.
So first
Riffle[Range@Length@s, s]
Then
Riffle[Range@Length@s, s] // Partition[#, 2] &
And so on. Hope this is helpful.
Correct answer by PaulCommentary on November 2, 2020
Maybe this way:
Join @@ MapIndexed[Thread[{#2[[1]], #1}] &, s]
{{1, 1}, {1, 2}, {1, 4}, {2, 7}, {2, 11}, {3, 3}, {3, 4}, {3, 12}}
Just in case you actually want to assemble a SparseArray
with "AdjacencyLists"
given by s
, you can do it like this:
A = With[{ci = Partition[Join @@ s, 1]},
SparseArray @@ {Automatic, {Length[s], Max[s]}, 0., {1, {
Prepend[Accumulate[Length /@ s], 0],
ci
}, ConstantArray[1, Length[ci]]}}
];
A["AdjacencyLists"] == s
A["NonzeroPositions"]
True
{{1, 1}, {1, 2}, {1, 4}, {2, 7}, {2, 11}, {3, 3}, {3, 4}, {3, 12}}
(And no, this use of SparseArray
is not documented.)
Answered by Henrik Schumacher on November 2, 2020
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP