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$
0

1 Answer 1

9
$\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$
1
  • $\begingroup$ Excellent answer. Very helpful. $\endgroup$ Jul 25, 2017 at 14:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.