6
$\begingroup$

When building a SparseArray, patterns of the form {i_, i_} and {i_, j_} are fine, but patterns like {i_, 2 i_} do not work:

SparseArray::posd: The left-hand side of {i_, 2 i_}->1 in {{i_, 2 i_}->1} is not a position or a pattern that will match the position of an element in an array with dimensions {4,4}.

m1 = SparseArray[{{i_, i_} -> 1}, {4, 4}];             (* OK *)
m2 = SparseArray[{{i_, 2 i_} -> 1}, {4, 4}];           (* error *)
m3 = SparseArray[{{i_, j_} /; j == 2 i -> 1}, {4, 4}]; (* OK *)
Map[MatrixForm, {m1, m2, m3}]

Sparse arrays

Why is this so? To me, {i_, 2 i_} -> 1 is easier to read than {i_, j_} /; j == 2 i -> 1.

$\endgroup$
10
$\begingroup$

For this reason

In[4]:= MatchQ[{1, 2}, {i_, 2 i_}]
Out[4]= False

In[5]:= MatchQ[{1, 2}, {i_, j_} /; j == 2 i]
Out[5]= True

Patterns are matched structurally, not mathematically. You need to write the pattern is such a way that it actually matches in positions in the matrix.

$\endgroup$
  • $\begingroup$ Excellent answer. Very helpful. $\endgroup$ – Jack LaVigne Jul 25 '17 at 14:25

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.