# Define a function with sparsearray

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}.

• 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. Mar 14, 2022 at 1:07
• 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."
– user49048
Mar 14, 2022 at 1:22

ClearAll[idx,ke,m,mat];