I have a function that I want to minimize numerically through an NMinimize command (because it's very complicated analytically). The minimizer call looks as follows:
NMinimize[{mat = func0[a, b, c, d, e, f]; Print[mat];
{ac0t, ac1t, ac2t, ac3t} = mat.{Ac0, Ac1, Ac2, Ac3};
{as0t, as1t, as2t, as3t} = mat.{As0, As1, As2, As3};
Total[({
a+b,
a^2+b^2,
...
})^2], constraints}, {a, b, c, d, e, f}, Method -> "NelderMead"]
So notice that I'm minimizing a sum of squares, but before calculating the sum of squares, I have to calculate stuff using a function func0
. func0
is defined as a numerical function:
func0[a_?NumericQ,b_?NumericQ,c_?NumericQ,d_?NumericQ,e_?NumericQ,f_?NumericQ]:=Module[{},...]
However, when it gets evaluated in the minimizer, it gets evaluated and held. So Print[mat] will result in func0[a, b, c, d, e, f]
, and not in a numerical value. While if I calculate this function outside NMinimze, it works fine. I can imagine that NMinimize is calling it with variables, and that's why it isn't working.
How can I tell NMinimize to take this only numerically?
Please advise. Thank you.
EDIT: As requested in comments, I'm adding an executable example of the problem:
func0[a_?NumericQ] := {{Sin[a Degree], Cos[a Degree]},{Sin[a Degree], Cos[a Degree]}}
NMinimize[{var = func0[a];
Print[var]; {aa, bb} = var.{1/Sqrt[2], 1/Sqrt[2]};
Total[{aa - bb, aa + bb
}^2], a > 0}, {a}, Method -> "NelderMead"]
If you execute this code, you'll see that an error will be thrown:
Set::shape: Lists {aa,bb} and func0[a].{1/Sqrt[2],1/Sqrt[2]} are not the same shape. >>
Which happens because func0[a] is being evaluated symbolically, while I must evaluate it numerically. Please note this is a simple example for the sake of argument. My func0
is very complicated and cannot be evaluated symbolically.
mat = func0[a, b, c, d, e, f]; Print[mat];
and givefunc0
some definition that doesn't match for six symbolic arguments, we will get the same result as you report here. So it isn't clear what, if anything, this has to do withNMinimize
. $\endgroup$ – Oleksandr R. Apr 24 '14 at 11:39NMinimize
doesn't haveHoldFirst
, so you certainly are calling it with symbolic parameters. $\endgroup$ – Oleksandr R. Apr 24 '14 at 12:03