MATLAB: How to fit a curve with other logic instead of least squares

curve fittingweighted fitting

Hey guys, I'm trying to fit a curve with dynamic weights. For a particular point, if the fitted value > the original value, then the weight of this point is w1, otherwise, the weight of this point is w2. Usually, the weights are static(be determined before fitting), but in this case, the weights are dynamic(be determined during fitting). Is there any ideas to implement this?
I know there is a mathematical methods can be used to avoid judgment statement:
value = w1*max(fitted-original,0)^2 + w2*max(original-fitted,0)^2;
But the problem is, all the fitting functions provided by Matlab are based on least squares method:
value = (fitted-original)^2;
How can I fit a curve with the former logic instead of the latter?

Best Answer

What you've described is a nonlinear least squares problem which can be written
min. || g(fitted-original)||^2
where
g(z) = sqrt(w2)*z, z>=0
= sqrt(w1)*z, z<=0
I believe this problem is only once-differentiable, since g() is only C^0 continuous at z=0. It would be better if you modified the problem so that g(z) is C^1 or C^2 continuous. Then you could apply any nonlinear solver in the Optimization Toolbox.
On the other, hand, you could always just try solving with the given g(z) and hope the algorithm iterations don't land on any points of non-differentiability.