6
$\begingroup$

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

$\endgroup$
11
$\begingroup$

This is precisely what SparseArray is good for:

SparseArray[data[[All, 1 ;; 2]] -> data[[All, 3]]]
| improve this answer | |
$\endgroup$
  • $\begingroup$ Wow! Awesome. Great function, thank you very much! $\endgroup$ – Cristhian Pardo Dec 7 '19 at 17:55
  • $\begingroup$ You're welcome. $\endgroup$ – Henrik Schumacher Dec 7 '19 at 18:39
3
$\begingroup$

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}}

| improve this answer | |
$\endgroup$

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.