1''
1''

Reputation: 27095

Plot curve fit with errorbars

When curve-fitting using the Matlab package cftool, there is an option to generate code corresponding to a fit. Here is a sample result:

%% Fit: 'myfit'.
[xData, yData, weights] = prepareCurveData( x, y, weights);

% Set up fittype and options.
ft = fittype( 'a^x+b', 'independent', 'x', 'dependent', 'y' );
opts = fitoptions( ft );
opts.Display = 'Off';
opts.Lower = [-Inf -Inf];
opts.StartPoint = [0 0];
opts.Upper = [Inf Inf];
opts.Weights = weights;

% Fit model to data.
[fitresult, gof] = fit( xData, yData, ft, opts );

% Plot fit with data.
figure( 'Name', 'myfit' );
h = plot( fitresult, xData, yData );
% Label axes
xlabel( 'x' );
ylabel( 'y' );
grid on

I would like to plot the same fit with custom error bars, using a separate vector of errors. Ordinarily, I would use the function errorbar() in place of plot(), but it does not accept fitobject objects like the fitresult in this code. In fact, the only reason this code works with plot() is that there's an overloaded version of plot() in the curve-fitting toolbox, totally separate from the normal plot(), that does accept these objects.

How can I plot cftool fits with errorbars?

Upvotes: 2

Views: 13030

Answers (3)

1''
1''

Reputation: 27095

To plot a fit and errorbars on the data, not the fit, use:

plot(fitresult, xData, yData);
hold on;
errorbar(xData,yData,errors, '.');

Upvotes: 2

Azeem Bande-Ali
Azeem Bande-Ali

Reputation: 305

Well you already have the fit, so you can just interpolate the y-values of the fit using feval(). Pair this data with your custom errors and send that to errorbar().

yFit = feval(fitresult, xData);
errorbar(xData,yFit,xError,yError);

Upvotes: 1

Rasman
Rasman

Reputation: 5359

I'm not sure how you want errorbars to be incorporated into your fit.

If you want to display both 'a' and 'b' with errorbars representing the CI, you can extract the CI using the confint function:

errorbar([fitresult.a; fitresult.b], diff(confint(fitresult))/2,'x')

Upvotes: 0

Related Questions