arraysoptimizationsyntaxwolfram-mathematica

Mathematica – Optimize over array variable


Suppose I have a function of some x and an array variable.

A = Array[a, 2];
f[x_] := (x-.5)^2 + a[1]^2 + a[2]^2

Now I would like to minimize over both, which leads to an error.

FindMinimum[f[x], {x, A}]

FindMinimum::nrlnum: The function value {0.707107,1.41421 a[1.]} is not a list of real numbers with dimensions {2} at {x,A} = {1.,1.}. >>

How would I have to write this?

In contrast, it works fine for non-array variables.

f[x_] := (x-.5)^2 + y^2 + z^2;
FindMinimum[f[x], {x, y, z}]
{0., {x -> 0.5, y -> 0., z -> 0.}}

And, curiously, it works fine if I have only the array variable.

A = Array[a, 3]
f := (a[3] - .5)^2 + a[1]^2 + a[2]^2
FindMinimum[f, A]
{0., {a[1] -> 0., a[2] -> 0., a[3] -> 0.5}}

Solution

  • I'd do :

    bigA = Array[a, 2];
    f[x_] := (x - .5)^2 + Total[bigA^2]
    
    FindMinimum[f[x], Flatten[{x, bigA}]]
    (* {0., {x -> 0.5, a[1] -> 0., a[2] -> 0.}} *)