# Array element problem in optimization

I have the following piece of code in Mathematica:

a = {1, 2};

b = {2, 3};

f[i_, j_] := a[[i]]^2 + b[[j]]^2;

Maximize[{f[i, j], 1 <= i <= 2 && 1 <= j <= 2}, {i, j}, Integers]


By running it I get:

Part::pspec: Part specification i is neither a machine-sized integer nor a list of machine-sized integers. >>

Part::pspec: Part specification j is neither a machine-sized integer nor a list of machine-sized integers. >>

Could anyone help me out?

• Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Read the faq! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign!
– user9660
Nov 24, 2014 at 20:02
• See question # 25152: Minimizing a Matrix Nov 24, 2014 at 20:23
• Could you please explain it more with a simple code? Tnx :) Nov 24, 2014 at 20:42

There are a couple of issues. One is that you need to bypass symbolic processing since entities like a[[i]] (with i symbolic) are not defined. We do this by forcing f to only work with explicit Integer inputs.

a = {1, 2};
b = {2, 3};
f[i_Integer, j_Integer] := a[[i]]^2 + b[[j]]^2;


The scond issue is that we now have an objective that is, in a sense, a procedural function. The function Minimize will not be able to do anything with this. But the numeric variant NMinimize can work with it.

NMaximize[{f[i, j], 1 <= i <= 2 && 1 <= j <= 2 && i \[Element] Integers && j \[Element] Integers}, {i, j}]

(* Out[228]= {13., {i -> 2, j -> 2}} *)