I'm confused by why the following doesn't work. I'm trying to numerically minimize a function that has an If statement in its definition, as follows:
means = {3.0, 1.5, 2.1};
sigmashi = {0.5, 0.4, 0.3};
sigmaslo = {0.4, 0.6, 0.25};
coeffA = {1.2, 3.2, 2.0};
coeffB = {0.3, -0.4, 0.5};
chisq[x_] :=
Sum[If[coeffA[[i]] x + coeffB[[i]] >
means[[i]], (coeffA[[i]] x + coeffB[[i]] - means[[i]])^2/
sigmashi[[i]]^2, (coeffA[[i]] x + coeffB[[i]] - means[[i]])^2/
sigmaslo[[i]]^2], {i, 1, Length[means]}]
FindMinimum[chisq[x], {x, 1.0}]
This returns a long string of error messages:
Part::pspec: Part specification i is neither a machine-sized integer nor a list of machine-sized integers. >> Part::pspec: Part specification i is neither a machine-sized integer nor a list of machine-sized integers. >> Part::pspec: Part specification i is neither a machine-sized integer nor a list of machine-sized integers. >> General::stop: Further output of Part::pspec will be suppressed during this calculation. >> FindMinimum::nrnum: The function value ({0.3,-0.4,0.5}[[i]]+1. <<1>>-{3.,1.5,2.1}[[i]])^2/{0.4,0.6,0.25}[[i]]^2+(2 ({0.3,-0.4,0.5}[[i]]+<<1>>-{3.,1.5,2.1}[[i]])^2)/{0.5,0.4,0.3}[[i]]^2 is not a real number at {x} = {1.}. >>
Why doesn't FindMinimum like my function? Why does it even care about the "i"? Is there a way to force Mathematica to do the minimization purely numerically, and not care about how the function computes its result? (NMinimize returns the same errors.)
I can kluge my way around this with the following alternative:
myif[z_, x_, y_] := ((Tanh[100 z] + 1)/2) x + ((Tanh[-100 z] + 1)/2) y
chisqA[x_] :=
Sum[myif[coeffA[[i]] x + coeffB[[i]] -
means[[i]], (coeffA[[i]] x + coeffB[[i]] - means[[i]])^2/
sigmashi[[i]]^2, (coeffA[[i]] x + coeffB[[i]] - means[[i]])^2/
sigmaslo[[i]]^2], {i, 1, Length[means]}]
But it isn't pretty.


chisq[x_?NumericQ]