3
votes

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?

1
if you are dealing with linear least squares you can do this from scratch using a vandermonde and weight matrix.mathematician1975
@mathematician1975, thanks but It'a not the case. I have a non-linear function which should fit to the dataset.user3355900
What does your cost function look like? Can you not get the weighting in there?Dan
@Dan, I have no idea how to get the weighting in the function. it is like a lorentzian function with a pick near the corner frequency. It can be called as yellow noise (link). It is a complicate function!user3355900

1 Answers

4
votes

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.