MATLAB: Plotting weighted residuals yields confusing results

cfitcurvefittingMATLABplot

When using the command:
plot(fitobj, x, y, 'x', 'residuals')
or
plot(fitobj, x, y, 'x', 'stresiduals')
with a weighted fit, I get results that are unexpected. Using the plot functions listed above, plots something that is proportional to the residual but neither the residual as given by the previous statement nor the unweighted residual. Furthermore, neither of the two statements are particularly affected by the size of the errors in the fit.

Best Answer

Given a data set with "y" and "x":
errormultiplier = 1000; % for debug use different values
sig_y = y_error*errormultiplier;
The "fit" function can be used to fit a curve to data and can return the vector of residuals for the provided data. In this case, a weighting factor is begin applied which will result in the residuals being weighted residuals. In the code snippet below, the weighted, non-standardized residuals will then be contained within the output variable "outp".
[fitobj, gof, outp] = fit(x, y,'poly1', 'Weights',(1./sig_y).^2)
Within the fit method, using the following least square algorithm, applies the weight to the "y" data:
squaredweights = sqrt(weight)
squaredweights =
1.0000e-4
weightdydata = ydata .* squaredweights;
This result in the "ydata" being scaled by a value of 1/10,000 then the rest of the information, like the residuals, are being calculated. When graphing between the two methods shown below (graphing via "fitobj" or "outp") this is the exact scaling factor. The "outp" object contains the results of the calculations with the weighted y-axis information. However, the "fitobj" just contains the generic fit equation.
Using the 'stresiduals' command, shown below, will plot the standardized residuals
plot(fitobj, x, y, 'x', 'stresiduals')
which performs the equivalent of the following code snippet:
stres = std(outp.residuals);
standardizedResiduals = outp.residuals./stres;
plot(x, outp.residuals./stres, 'x')
This plot is standardized with respect to the residuals, so it will be unaffected by any sort of multiplier applied to it.
Because the "fitobj" only contains the generic fit equation, when you plot "x" and "y" with the "fitobj", the "y" data remains un-weighted and the residuals that are plotted will remain un-weighted. This is done for modularity.
plot(fitobj, x, y, 'x', 'residuals')
By using the "outp" object we then get the weighted residuals graphed. This can be done through the following method:
plot(x, outp.residuals, 'x');