# How to delay evaluation of Tuples[list,n] when n is a variable to be optimized through NMinimize?

I am trying to do a linear optimization on a variable i where an intermediate variable v is needed:

Reproduce[]:=
Module[{v,c1,obj,var},
v = Tuples[Range[3,4],i];
c1 = 2 <= i <= 10;
obj = Total[Flatten[v]+i];
var = { i \[Element] NonNegativeIntegers };
NMinimize[{obj,c1 }, var]
]
Reproduce[]


In its current form the code does not run and throws a Tuples::ilsmn: Single or list of non-negative machine-sized integers expected at position 2 of Tuples[{3,4},i].

My assumption is that Tuples[list,n] requires an integer, but I am trying to feed it with an expression/unevaluated-variable (whatever this means in Mathematica language).

How do I get the desired behavior?

You have some wrong syntax, and you also have to define the objective function as one that will only accept numerical inputs:

Reproduce[] := Module[{v, c1, obj, var},
v[i_?NumericQ] := Tuples[Range[3, 4], i];
c1 = 2 <= i <= 10;
obj[i_?NumericQ] := Total[Flatten[v[i]] + i];
NMinimize[{obj[i], c1, i \[Element] NonNegativeIntegers}, i];
]
Reproduce[]
(* {44., {i -> 2}} *)

• @WaterFox I can't guarantee that this will yield the correct answer, though, since I don't know what you're actually trying to do. Some basic testing indicates that the minimum always happens for $i=2$, and it looks like it takes a long time to run of you use something like Range[2, 7]. Apr 4 at 3:01
• Oh I see so you transform everything to a function of the actual variable. That's smart! I think you solved my problem, it was really a syntax problem - the actual optimization is a detail, I gave here a dummy equivalent that is a bit nonsensical. It should not take too long as I can guarantee that Range[a,a+1] applies :) Apr 4 at 18:31
• Does obj has to be a function of all variables defined in vars ? Apr 4 at 19:37
• I'm not sure what you mean. Since v us a function of i, obj is strictly a function of i. What's important is that obj is a function of i explicitly since that's the variable you're minimizing with respect to, and that it will only be called if fed with a numeric value. Apr 4 at 20:23
• @WaterFox That seems significantly more complicated due to the nesting. You can't minimize with respect to a vector in Mathematica, I think; you have to minimize with respect to the components of the vector. The problem, then, is that there are a variable number of components depending on the value of $i$, and it's not clear to me how you would implement that in Mathematica. I'm sure it's possible, but I can't think of an obvious way to make that work. Apr 5 at 18:05