weighted curve fitting with lsqcurvefit
matlab
Solution
For doing weighting, I find it much easier to use `lsqnonlin` which is the function that `lsqcurvefit` calls to do the actual fitting.
You first have to define a function that you are trying to minimize, ie. a cost function. You need to pass in your weighting function as an extra parameter to your function as a vector:
x = yourIndependentVariable;
y = yourData;
weightVector = sqrt(abs(1./y));
costFunction = @(A) weightVector.*(yourModelFunction(A) - y);
aFit = lsqnonlin(costFunction,aGuess);
The reason for the square root in the weighting function definition is that `lsqnonlin` requires the residuals, not the squared residuals or their sum, so you need to pre-unsquare the weights.
Alternatively, if you have the Statistics Toolbox, you can use `nlinfit` which will accept a weighting vector/matrix as one of the optional inputs.
Problem
I wanted to fit an arbitrary function to my data set. Therefore, I used `lsqcurvefit` in MATLAB. Now I want to give weight to the fit procedure, meaning when curve fitting function (`lsqcurvefit`) is calculating the residue of the fit, some data point are more important than the others. To be more specific I want to use statistical weighting method. ``` w=1/y(x), ``` where `w` is a matrix contains the weight of each data point and `y` is the data set. I cannot find anyway to make weighted curve fitting with `lsqcurvefit`. Is there any trick I should follow or is there any other function rather than `lsqcurvefit` which do it for me?