There is list containing some $(i,j)$ values of indices. Now i want to create a matrix of dimension n $\times$ m whose entries are 1 for the indices corresponding to the given list otherwise its zero.
For e.g if the list is as given below
list = {{1, 1}, {1, 2}, {2, 1}, {3, 3}};
And if $n=m=3$ then the output should be
{{1, 1, 0}, {1, 0, 0}, {0, 0, 1}}
I was able to do this as shown below but i believe this could be achieved with a shorter and a more elegant code. Maybe a one liner.
cHeck[n1_, n2_] := Module[{flag = 0, list, i},
list = {{1, 1}, {1, 2}, {2, 1}, {3, 3}};
For[i = 1, i <= Length[list], i++,
Which[{n1, n2} === list[[i]], flag = 1]
];
flag
]
A[n_, m_] := Table[cHeck[i, j], {i, 1, n}, {j, 1, m}]
A[3, 3]
(*{{1, 1, 0}, {1, 0, 0}, {0, 0, 1}}*)
SparseArray[# -> 1 & /@ list, {n, m}, 0]. – b.gates.you.know.what Feb 07 '14 at 14:49Band, as well as many uses ofSparseArrayas part of a larger answer, but I did not fine one that I felt was a duplicate. – Mr.Wizard Feb 07 '14 at 15:59f1? Just withlist -> 1instead of individually setting them? Feel free to reopen it if you feel it isn't addressed by the other one. – rm -rf Feb 07 '14 at 16:34ReplacePartandSparseArraycan accept the formpositionlist -> valuewithout the need for mapping or threading. The first comment above shows that people are not all aware of this. Closer are some of the answers I found usingBand. I am going to reopen this for now; if you come across another Q&A that is not overly involved that clearly shows the syntax I describe please close it again. – Mr.Wizard Feb 07 '14 at 16:42