Skip to main content

mathematical optimization - Minimizing using indices, error: Part::pkspec1: The expression cannot be used as a part specification


I want to use Minimize where the variables to minimize are indices pointing into an array.


Here a MWE that hopefully shows what my problem is.


vars = u@# & /@ Range[3];
cons = Flatten@ { Table[(u[j] != #) & /@ vars[[j + 1 ;; -1]], {j, 1,
3 - 1}],
1 <= # <= 3 & /@ vars };
vec1 = {1, 2, 3}; vec2 = {1, 2, 3};
Minimize[{Total@((vec1[[#]] - vec2[[u[#]]])^2 & /@ Range[1, 3]),
cons}, vars, Integers]


The error I get:


Part::pkspec1: The expression u[1] cannot be used as a part specification. >>

Answer



Ok,


it seems that one can get around Mathematica trying to evaluate vec2[[u[1]]] too early by using the function Indexed[vec2,u[1]].


The working MWE would then look like the following:


vars = u@# & /@ Range[3];
cons = Flatten@{ Table[(u[j] != #) & /@ vars[[j + 1 ;; -1]], {j, 1,
3 - 1}],

1 <= # <= 3 & /@ vars};
vec1 = {1, 2, 3}; vec2 = {1, 2, 3};
NMinimize[ {Total@((vec1[[#]] - Indexed[vec2, u[#]])^2 & /@
Range[1, 3]), cons}, vars, Integers ]

which yields correctly:


{0., {u[1] -> 1, u[2] -> 2, u[3] -> 3}}

See also an answer to this post by Mr.Wizard:


Prevent Part[] from trying to extract parts of symbolic expressions



Comments