# Help on how to write a function to be used with NMinimize

I need some help to write a proper function to be used as a parameter on NMinimize. Here is the code of the function to be minimized (Please correct, optimize and rewrite the code if you want to - I need to understand how to write proper Mathematica code).

plot[τ_, Ω_] := Module[{arg, abs, aux},
{arg, abs} =
Factor[Together[ComplexExpand[Through[{Arg, Abs}[(1 + I*2*Ω)/(1 + I*2*τ*Ω)]]]]];
aux = arg/Degree;
aux = If[aux < 0, aux = 360 - aux, aux];
{aux, 20*Log10[abs]}]

modFunction1[kc_, gp_, ω_, pm_, variable_:s] := Module[{arg, abs, aux},
{arg, abs} =
Factor[Together[ComplexExpand[Through[{Arg, Abs}[kc*gp /. variable -> I*ω]]]]];
aux = (-arg)*(180/Pi) + pm - 180;
aux = If[aux < 0, 360 + aux, aux];
{-20*Log10[abs], aux}];

functionF1[kc_, gp_, ω_, pm_, variable_:s, τ_, Ω_] := Module[{a, b, c, d},
{a, b} = N[modFunction1[kc, gp, ω, pm, variable]];
{d, c} = N[plot[τ, Ω]];
(a - c)^2 + (b - d)^2];


and finally

NMinimize[functionF1[50, 100/(s*(s + 5)*(s + 10)), 9, 42, τ, Ω],
{{τ, 10.5, 10.6}, {Ω, -0.1988, -0.1987}}]


NMinimize returns

NMinimize::nnum: "The function value 0.000459846 +(54.9326 -aux\$584644)^2 is not a number at {[Tau],[CapitalOmega]} = {10.5919,-0.198714}"

but evaluating functionF1 on those same values returns a real number.

What am I missing? Any comment on how to write the code is most welcome. I definitely need some guide on how to write proper functions.

-
You need to rewrite your function such that there are only numeric arguments. If you need to work with symbolic variables then do this outside of NMinimize, i.e., calculate your objective function. – Rolf Mertig Feb 2 at 0:54
In plot you write aux = If[aux < 0, aux = 360 - aux, aux];. Perhaps you meant to write aux = If[aux < 0, 360 + aux, aux] as you did in modFunction1? – m_goldberg Feb 2 at 2:12
functionF1[kc_, gp_, \[Omega]_, pm_, variable_: s, \[Tau]_?NumericQ, \[CapitalOmega]_?NumericQ] so that it stays symbolic for non-numeric arguments, and you get {1.33561*10^-13, {\[Tau] -> 10.5662, \[CapitalOmega] -> -0.198671}} – Rojo Feb 2 at 4:11
@Rojo - Many thanks - I have changed all the other functions to accomodate ?NumericQ where it is needed and Mathematica had not problem to find the minimum (it took some time though). – Ed Mendes Feb 2 at 15:48
@Rolf - Many thanks. – Ed Mendes Feb 2 at 15:49
show 1 more comment