Generating a (sparse?) array from data

posval = Join[List /@ RandomSample[Tuples[Range[5], {2}], 10], 
   List/@RandomInteger[9, 10], 2]

{{{2, 4}, 3}, {{2, 1}, 8}, {{3, 5}, 4}, {{2, 3}, 3}, {{5, 5}, 4}, {{3, 2}, 8}, {{4, 5}, 8}, {{3, 1}, 6}, {{2, 5}, 2}, {{5, 1}, 8}}

dims = Max /@ Transpose[posval[[All, 1]]];
sa = SparseArray[Rule @@@ posval, dims];

SparseArray[<10>, {5, 5}]

TeXForm @ MatrixForm @ sa

$$\left( \begin{array}{ccccc} 0 & 0 & 0 & 0 & 0 \\ 8 & 0 & 3 & 3 & 2 \\ 6 & 8 & 0 & 0 & 4 \\ 0 & 0 & 0 & 0 & 8 \\ 8 & 0 & 0 & 0 & 4 \\ \end{array} \right)$$


Another possibility is

SparseArray[Rule @@ Transpose[posval]]

I think the input syntax that gets processed the quickest among the documented ones would be

SparseArray[pos -> vals , dims]

where pos is a list of positions and vals is a list of values. This way, pos and vals can be PackedArrays which can be processed much faster. A list of the form you described cannot be packed in general. So better not generate it this way. Mapping Rule on the position-value pairs also unpacks arrays. Generate pos and vals independently. In general, this will be much faster.

For additive matrix assembly, see also here.


For a list of the form: list={{pos_1,val_1},{pos_2,val_2}}

How about SparseArray[Map[#[[1]] -> #[[2]] &, list]] ?