4
$\begingroup$

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?

$\endgroup$
2
  • $\begingroup$ 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! $\endgroup$
    – Michael E2
    Commented Jun 30, 2016 at 4:23
  • $\begingroup$ You might want to look up IncidenceMatrix[]. $\endgroup$ Commented Jun 30, 2016 at 4:55

5 Answers 5

5
$\begingroup$
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}*)
$\endgroup$
2
$\begingroup$
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}

$\endgroup$
2
$\begingroup$

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
Thread[{%%, %}]
Thread[% -> #] &@%%%%

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

$\endgroup$
1
$\begingroup$
MapIndexed[Splice @ Thread[Tuples @ {##} -> 1] &] @ l
{{a, 1} -> 1, {b, 1} -> 1,   
 {c, 2} -> 1, {d, 2} -> 1,   
 {e, 3} -> 1, {f, 3} -> 1}
$\endgroup$
1
$\begingroup$

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

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.