1
votes

I am using Matlab's curve fitting tool, cftool, to fit a set of points which I have. The problem I am facing is that the generate code function will not give me the same fit as produced in the cftool.

This is not what I want because I want to be able to retrieve the data from the residual plot. I could also just copy the function from cftool and do it manually. But I do not understand why the generated code will not just give me the same curve fit.

The cftool session file: http://dl.dropbox.com/u/20782274/test.sfit

The generated code from Matlab:

function [fitresult, gof] = createFit1(Velocity, kWhPerkm)
%CREATEFIT1(VELOCITY,KWHPERKM)
%  Create a fit.
%
%  Data for 'untitled fit 3' fit:
%      X Input : Velocity
%      Y Output: kWhPerkm
%  Output:
%      fitresult : a fit object representing the fit.
%      gof : structure with goodness-of fit info.
%
%  See also FIT, CFIT, SFIT.

%  Auto-generated by MATLAB on 02-Dec-2012 16:36:19


%% Fit: 'untitled fit 3'.
[xData, yData] = prepareCurveData( Velocity, kWhPerkm );

% Set up fittype and options.
ft = fittype( 'a/(0.008*x) + c*x^2 + d*90', 'independent', 'x', 'dependent', 'y' );
opts = fitoptions( ft );
opts.DiffMaxChange = 0.01;
opts.Display = 'Off';
opts.Lower = [-Inf -Inf -Inf];
opts.MaxFunEvals = 1000;
opts.MaxIter = 1000;
opts.StartPoint = [0 0 0];
opts.Upper = [Inf Inf Inf];

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

% Create a figure for the plots.
figure( 'Name', 'untitled fit 3' );

% Plot fit with data.
subplot( 2, 1, 1 );
plot( fitresult, xData, yData, 'predobs' );
% Label axes
xlabel( 'Velocity' );
ylabel( 'kWhPerkm' );
grid on

% Plot residuals.
subplot( 2, 1, 2 );
plot( fitresult, xData, yData, 'residuals' );
% Label axes
xlabel( 'Velocity' );
ylabel( 'kWhPerkm' );
grid on

The curve I get with the generated code: http://i.stack.imgur.com/65d1P.jpg

The curve I need: http://i.stack.imgur.com/p3Egp.jpg

So does anyone know what goes wrong?

-edit- And the Velocity and WhPerkm data file: http://dl.dropbox.com/u/20782274/data.mat

1
When I use the data from dl.dropbox.com/u/20782274/data.mat in CFTOOL, I get what looks like a good fit: i.stack.imgur.com/DnUND.png. When I use the data in the session (dl.dropbox.com/u/20782274/test.sfit ) and the generated code, I get another good fit: i.stack.imgur.com/O9USJ.png. Can you check the data that you using with the generated code?ManWithSleeve

1 Answers

2
votes

RE: I want to be able to retrieve the data from the residual plot

One way to do this is:

  1. Select "Save to Workspace..." from the Fit menu
  2. Ensure that "Save fit output to MATLAB struct named" is checked.
  3. Note the name of variable. By default, it is output.
  4. Click "OK" to send data to the MATLAB workspace.

In the MATLAB workspace, the residuals will be in output.residuals. For your example, you can plot the residuals via, e.g.,

>> plot( Velocity, output.residuals, '.' )