7

I have a list:

{{pos_1,val_1},{pos_2,val_2},...}

and would like to generate an array of dimension d, with values val_i at positionspos_i, the rest being filled with 0. I would assume that I shall use SparseArray but this function has a different form of argument:

{pos_1->val_1,pos_2->val_2,...}

Is there any simple way to transform one type of the argument into the other, or completely different approach shall be undertaken?

kglr
  • 394,356
  • 18
  • 477
  • 896
drer
  • 719
  • 3
  • 9

3 Answers3

5
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)$$

kglr
  • 394,356
  • 18
  • 477
  • 896
5

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.

Henrik Schumacher
  • 106,770
  • 7
  • 179
  • 309
4

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

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

Dunlop
  • 4,023
  • 5
  • 26
  • 41
  • I have tried and got the message List expected at position 1 in SparseArray. Can you give a working example? – drer Feb 28 '18 at 15:22
  • sorry made a typo in the equation. I will add a full working example when I get access to MMA again – Dunlop Feb 28 '18 at 15:55