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.
plot
you writeaux = If[aux < 0, aux = 360 - aux, aux];
. Perhaps you meant to writeaux = If[aux < 0, 360 + aux, aux]
as you did inmodFunction1
? $\endgroup$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}}
$\endgroup$