1
$\begingroup$

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!

$\endgroup$
  • 3
    $\begingroup$ SparseArray[A -> 77] ? $\endgroup$ – Simon Woods Jun 12 '14 at 7:51
  • $\begingroup$ @SimonWoods So simple?! Thank you very much, it was exactly I was looking for. $\endgroup$ – Yasha Gindikin Jun 12 '14 at 8:04
7
$\begingroup$

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} *)
$\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.