# Build a matrix from the coordinates of its elements and complete it with zeros

Suppose that I have a data set data (input):

data = {{1, 1, 1}, {2, 1, 2}, {2, 2, 5}, {2, 3, 3}, {2, 4, 4}, {2, 6, 1}, {3,
2, 3}, {3, 3, 3}, {3, 4, 12}, {3, 6, 7}, {4, 4, 4}, {4, 6, 6}, {5,
6, 1}}


and I want to build from it a matrix mat (output):

mat = {{1,0,0,0,0},{2,5,3,4,0,1},{0,3,3,12,0,7},{0,0,0,4,0,6},{0,0,0,0,0,1}}


where the rule of construction is the following:

the element {x,y,z} of data is mapped onto the element z of mat where z = mat[[x,y]] (i.e z is in the x-row and in the y-column of mat) and all the other elements are zeroes.

I think that that ArrayPad could work, but I dont see how quikly I can get it.

Thanks

This is precisely what SparseArray is good for:

SparseArray[data[[All, 1 ;; 2]] -> data[[All, 3]]]

• Wow! Awesome. Great function, thank you very much! Dec 7, 2019 at 17:55
• You're welcome. Dec 7, 2019 at 18:39

Another way

data = {{1, 1, 1}, {2, 1, 2}, {2, 2, 5}, {2, 3, 3}, {2, 4, 4}, {2, 6, 1}, {3, 2, 3}, {3, 3, 3}, {3, 4, 12}, {3, 6, 7}, {4, 4, 4}, {4, 6, 6}, {5, 6, 1}};

dims = Max /@ Transpose@data[[;; , ;; 2]]

mat = ConstantArray[0, dims];
(mat[[#1, #2]] = #3) & @@@ data;
mat


{5,6}

{{1, 0, 0, 0, 0, 0}, {2, 5, 3, 4, 0, 1}, {0, 3, 3, 12, 0, 7}, {0, 0, 0, 4, 0, 6}, {0, 0, 0, 0, 0, 1}}