I have a user defined function h[i_,j_] and I would like to find its minimum value over all integers $1 \leq i \leq 100$ and $1 \leq j \leq 100$ and $j \leq i$. I would just like Mathematica to try all the possibilities rather than attempt any symbolic minimization. How can you do that?
3 Answers
If you like loops, you could just go through all combinations and memorize the minimum value and position:
h[x_, y_] := ((x - 30)^2 + (y - 10)^2);
min = h[1, 1];
pos = {1, 1};
Do[If[h[i, j] < min, min = h[i, j]; pos = {i, j}], {i, 100}, {j, 100}];
And then min
is 0 and pos
is {30,10}
as expected. With this approach you don't need to allocate the memory as in the Table
example.
Not so fast for this specific example but definitely more beautiful is using Minimize
although you don't wanted this
Minimize[{h[x, y], 1 <= x <= 100 && 1 <= y <= 100}, {x, y}, Integers]
-
$\begingroup$ Thank you. The problem with Minimize is that it doesn't do anything in my case. $\endgroup$– SimdCommented Apr 16, 2013 at 19:31
As suggested in the comments, Table
can be used to generate the matrix. To find the {i,j}
pair corresponding to the minimum value, a combination of Min
and Position
can be used.
tbl = Table[h[i, j], {i, 1, 100}, {j, 1, i}];
Position[tbl, Min@tbl, {2}]
If you don't need to find the parameters, but only the minimum value, you could save memory by finding the minimum for each row. Compare:
h[x_, y_] := ((x - 30)^2 + (y - 10)^2);
n = 1500;
Min @ Table[Min @ Array[h[i, #] &, i], {i, n}]
MaxMemoryUsed[]
0 15405976
Min @ Table[h[i, j], {i, n}, {j, i}];
MaxMemoryUsed[]
162985456
Table
. $\endgroup$