# Converting a list of lists of indices into a sparse matrix of ones and zeros

I have data formatted like {{a,b},{c,d},{e,f}} where each entry is an integer. I need to turn this in to a sparse array with entries {a,1}->1, {b,1}->1, {c,2}->1, ... {f,3}->1 and so on. In other words, if $x$ is an integer in the $j$th list, we need coordinate $(x,j)$ of the sparse matrix to be $1$.

How should I accomplish this?

• Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Take the tour! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! Commented Jun 30, 2016 at 4:23
• You might want to look up IncidenceMatrix[]. Commented Jun 30, 2016 at 4:55

l = {{a, b}, {c, d}, {e, f}};
Flatten[MapIndexed[{#1, #2[[1]]} -> 1 &, l, {2}], 1]

(*{{a, 1} -> 1, {b, 1} -> 1, {c, 2} -> 1, {d, 2} -> 1, {e, 3} ->
1, {f, 3} -> 1}*)

list = {{a, b}, {c, d}, {e, f}};


Using ReplacePart

Join @@ ReplacePart[list, {i_, j_} :> {list[[i, j]], i} -> 1]


{{a, 1} -> 1, {b, 1} -> 1, {c, 2} -> 1, {d, 2} -> 1, {e, 3} -> 1, {f, 3} -> 1}

Another way is the following:

{{a, b}, {c, d}, {e, f}};
Table[i, {i, 1, First@Dimensions[%]}, {j, 1, Last@Dimensions[%]}]
Table[1, Total[Length /@ %%]]
%%% // Flatten
%%% // Flatten


{{a, 1} -> 1, {b, 1} -> 1, {c, 2} -> 1, {d, 2} -> 1, {e, 3} -> 1, {f, 3} -> 1}

MapIndexed[Splice @ Thread[Tuples @ {##} -> 1] &] @ l

{{a, 1} -> 1, {b, 1} -> 1,
{c, 2} -> 1, {d, 2} -> 1,
{e, 3} -> 1, {f, 3} -> 1}


Another way is the following:

l = {{a, b}, {c, d}, {e, f}};

Flatten[Table[{l[[i, j]], i} -> 1, {i, Length[l]}, {j, Length[l[[i]]]}], 1]

(*{{a, 1} -> 1, {b, 1} -> 1, {c, 2} -> 1, {d, 2} -> 1, {e, 3} -> 1, {f, 3} -> 1}*)