Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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!

share|improve this question
3  
SparseArray[A -> 77] ? –  Simon Woods Jun 12 at 7:51
    
@SimonWoods So simple?! Thank you very much, it was exactly I was looking for. –  Yasha Gindikin Jun 12 at 8:04

1 Answer 1

up vote 5 down vote accepted

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} *)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.