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?

  • $\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 Jun 30 '16 at 4:23
  • $\begingroup$ You might want to look up IncidenceMatrix[]. $\endgroup$ – J. M.'s technical difficulties Jun 30 '16 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}*)
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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