1
$\begingroup$

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.

$\endgroup$
1
  • 1
    $\begingroup$ To understand how to do this, have a look at the doc page for Thread and MapIndexed. $\endgroup$
    – Jason B.
    Commented Jul 21, 2020 at 16:35

2 Answers 2

2
$\begingroup$

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.

$\endgroup$
1
  • $\begingroup$ I tried both your method and the other answer's method, and used the other because it was more convenient. However, I still tried yours, and I learned a bit from your answer, so I will accept yours. I hope @Henrik Schumacher is OK with this. $\endgroup$ Commented Jul 22, 2020 at 5:06
3
$\begingroup$

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.)

$\endgroup$
1
  • $\begingroup$ Your method was very useful; please see my comment on the accepted answer. $\endgroup$ Commented Jul 22, 2020 at 5:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.