I am trying to define a function using SparseArray, but the entries were defined before. How can I avoid this error?

Code is:

ix = {i1, i2, i3};
idx = Flatten[Outer[{#1, #2} &, ix, ix], 1]
ke = Array[c, {3, 3}] // Flatten
m = MapThread[#1 -> #2 &, {idx, ke}]

mat[{i1_, i2_, i3_}, c_, nx_] := SparseArray[m, nx]
mat[{1, 2, 3}, c, 10]

During evaluation of In[99]:= SparseArray::posd: The left-hand side of {i1,i1}->c[1,1] in {{i1,i1}->c[1,1],{i1,i2}->c[1,2],{i1,i3}->c[1,3],{i2,i1}->c[2,1],{i2,i2}->c[2,2],{i2,i3}->c[2,3],{i3,i1}->c[3,1],{i3,i2}->c[3,2],{i3,i3}->c[3,3]} is not a position or a pattern that will match the position of an element in an array with dimensions {10,10}.

  • 1
    $\begingroup$ You are defining the function with one set of arguments and then only using one of these in your actual function. What you are doing, syntactically, is not correct. It remains to be seen if your overall method is correct, however, but it cannot overcome the general syntax issues present. $\endgroup$ Commented Mar 14, 2022 at 1:07
  • 1
    $\begingroup$ To add a brief comment to the previous one by @CATrevillian, if I execute the first four lines of your code and then run SparseArray[m] I get an error. Namely "The left-hand side of {i1,i1}[1]->{i1,i1}[2] in \ {{i1,i1}[1]->{i1,i1}[2],{i1,i2}[1]->{i1,i2}[2],{i1,i3}[1]->{i1,i3}[2],\ {i2,i1}[1]->{i2,i1}[2],{i2,i2}[1]->{i2,i2}[2],{i2,i3}[1]->{i2,i3}[2],{\ i3,i1}[1]->{i3,i1}[2],{i3,i2}[1]->{i3,i2}[2],{i3,i3}[1]->{i3,i3}[2]} \ is not a position or pattern that will match a position." $\endgroup$
    – user49048
    Commented Mar 14, 2022 at 1:22

1 Answer 1


I corrected some of the syntax issues in your code. While this can likely be improved, I think it is beneficial to see what precisely can be changed to make your code able to run. Please find it below, and let me know if you have any questions:



mat[m[idx[{1,2,3}],ke[c]], 10]

Your Answer

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

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