# Devising a sparse array rule

Suppose I have a matrix

A={{1, 2}, {3, 4}}


that defines the positions of non-zero values in a sparse array:

S=SparseArray[Table[p1 = A[[i, 1]]; p2 = A[[i, 2]]; {p1, p2} -> 77, {i, Dimensions[A][[1]]}]];
ArrayRules@S
{{1, 2} -> 77, {3, 4} -> 77, {_, _} -> 0}


Is it possible to construct such a sparse array without explicitly building the table of correspondence, by using a single rule that extracts the positions of non-zero elements from matrix A? Mathematica documentation shows examples of such rules, e.g.

SparseArray[{{i_, j_} /; Abs[i - j] <= 1 -> -2 + 3 Abs[i - j]}, {5,5}]


How should a similar rule be devised for my case? Thank you!

• SparseArray[A -> 77] ? Jun 12, 2014 at 7:51
• @SimonWoods So simple?! Thank you very much, it was exactly I was looking for. Jun 12, 2014 at 8:04

The documentation for SparseArray shows this form:

SparseArray[{pos1, pos2, ...} -> {val1, val2, ...}]

The list of positions is what you have in A, so you could do something like:

SparseArray[A -> {77, 88}] // ArrayRules
(* {{1, 2} -> 77, {3, 4} -> 88, {_, _} -> 0} *)


If the values are all the same, as in your example, you can supply just the single value rather than a list:

SparseArray[A -> 77] // ArrayRules
(* {{1, 2} -> 77, {3, 4} -> 77, {_, _} -> 0} *)