Products & Services Solutions Academia Support User Community Company

Learn more about Curve Fitting Toolbox   

Generating M-files From Curve Fitting Tool

This section describes how to generate and use MATLAB code from an interactive session in Curve Fitting Tool.

For Surface Fitting Tool, see Generating M-Files from the Surface Fitting Tool.

Overview

One way to quickly assemble curve fitting objects and methods into useful programs is to generate an M-file from a session in Curve Fitting Tool. In this way, interactive analysis of a single data set is transformed into a reusable function for batch processing of multiple data sets. The generated M-file can be used without modification, or it can be edited and customized as needed.

To generate an M-file from a session in Curve Fitting Tool, select the menu item File > Generate M-file.

The M-file captures the following information from Curve Fitting Tool:

You can recreate your Curve Fitting Tool session by calling the M-file from the command line with your original data as input arguments. You can also call the M-file with new data, applying the assembled curve fitting methods to recompute curve fitting objects.

The Generated M-file

M-files generated from Curve Fitting Tool are constructed from building-block components of code, which you can analyze, modify, and reuse in your own M-files. The components of the generated M-file provide good examples of how to assemble curve fitting objects and methods to perform basic tasks. The larger M-file shows you how to assemble those tasks into a complete analysis of your data.

For example, the following M-file was generated from a session in Curve Fitting Tool that imported the data from census.mat and fit a custom nonlinear model of the form y = a(xb)3:

function myfit(cdate,pop)
%MYFIT    Create plot of datasets and fits
%   MYFIT(CDATE,POP)
%   Creates a plot, similar to the plot in the main curve fitting
%   window, using the data that you provide as input.  You can
%   apply this function to the same data you used with cftool
%   or with different data.  You may want to edit the function to
%   customize the code and this help message.
%
%   Number of datasets:  1
%   Number of fits:  1


% Data from dataset "pop vs. cdate":
%    X = cdate:
%    Y = pop:
%    Unweighted
%
% This function was automatically generated on 11-Sep-2007 01:07:11

% Set up figure to receive datasets and fits
f_ = clf;
figure(f_);
set(f_,'Units','Pixels','Position',[439.6 193.6 814.4 576.8]);
legh_ = []; legt_ = {};   % handles and text for legend
xlim_ = [Inf -Inf];       % limits of x axis
ax_ = axes;
set(ax_,'Units','normalized','OuterPosition',[0 0 1 1]);
set(ax_,'Box','on');
axes(ax_); hold on;


% --- Plot data originally in dataset "pop vs. cdate"
cdate = cdate(:);
pop = pop(:);
h_ = line(cdate,pop,'Parent',ax_,'Color',[0.333333 0 0.666667],...
     'LineStyle','none', 'LineWidth',1,...
     'Marker','.', 'MarkerSize',12);
xlim_(1) = min(xlim_(1),min(cdate));
xlim_(2) = max(xlim_(2),max(cdate));
legh_(end+1) = h_;
legt_{end+1} = 'pop vs. cdate';

% Nudge axis limits beyond data limits
if all(isfinite(xlim_))
   xlim_ = xlim_ + [-1 1] * 0.01 * diff(xlim_);
   set(ax_,'XLim',xlim_)
else
    set(ax_, 'XLim',[1788, 1992]);
end


% --- Create fit "fit 1"
ok_ = isfinite(cdate) & isfinite(pop);
if ~all( ok_ )
    warning( 'GenerateMFile:IgnoringNansAndInfs', ...
        'Ignoring NaNs and Infs in data' );
end
st_ = [0.51510504095942344 0.35210694524343056 ];
ft_ = fittype('a*(x-b)^3',...
     'dependent',{'y'},'independent',{'x'},...
     'coefficients',{'a', 'b'});

% Fit this model using new data
cf_ = fit(cdate(ok_),pop(ok_),ft_,'Startpoint',st_);

% Or use coefficients from the original fit:
if 0
   cv_ = { 1.3594203554767276e-005, 1724.6959436137356};
   cf_ = cfit(ft_,cv_{:});
end

% Plot this fit
h_ = plot(cf_,'fit',0.95);
legend off;  % turn off legend from plot method call
set(h_(1),'Color',[1 0 0],...
     'LineStyle','-', 'LineWidth',2,...
     'Marker','none', 'MarkerSize',6);
legh_(end+1) = h_(1);
legt_{end+1} = 'fit 1';

% Done plotting data and fits.  Now finish up loose ends.
hold off;
leginfo_ = {'Orientation', 'vertical', 'Location', 'NorthEast'}; 
h_ = legend(ax_,legh_,legt_,leginfo_{:});  % create legend
set(h_,'Interpreter','none');
xlabel(ax_,'');               % remove x label
ylabel(ax_,'');               % remove y label

A quick look through the code shows that it has automatically assembled for you many of the Curve Fitting Toolbox curve fitting methods, such as fitoptions, fittype, fit, and plot.

Running the Generated M-file

To run the generated M-file without modification, and reproduce your original Curve Fitting Tool session, type:

load census
myfit(cdate,pop)

To run the M-file without modification on new data, pass the new data to the function as input arguments:

newpop = pop + 50*randn(size(pop));
myfit(cdate,newpop)

The M-file recomputes the cfit object for the fit and displays the new data with the new fit.

Components of the Generated M-File

It is useful to take a closer look at the components of the generated M-file, to understand the role that each component plays in the overall visualization and analysis of the data. This allows you to change the M-file, and customize it to your needs.

The M-file begins with a function declaration:

function myfit(cdate,pop)

The function accepts predictor and response data for a predefined fit type. The inputs are called cdate and pop because those were the predictor and response variables used in Curve Fitting Tool session that produced the file. If you like, you can find and replace the input names here and elsewhere in the file to indicate a more generic application of the fit.

Note that the file, as generated, returns no outputs. It simply applies the fit to the input data and displays the results.

The next component of the M-file, after the help information, is the following:

% Set up figure to receive datasets and fits
f_ = clf;
figure(f_);
set(f_,'Units','Pixels','Position',[439.6 193.6 814.4 576.8]);
legh_ = []; legt_ = {};   % handles and text for legend
xlim_ = [Inf -Inf];       % limits of x axis
ax_ = axes;
set(ax_,'Units','normalized','OuterPosition',[0 0 1 1]);
set(ax_,'Box','on');
axes(ax_); hold on;

These are Handle Graphics® methods, applied to Handle Graphics objects that encapsulate information on the display of the figure window, the legend, and the axes. This component of the M-file creates a figure for plotting that mimics the Plotting GUI in Curve Fitting Tool. Note that at the end of this component hold is toggled on. This allows the input data and the fit to be plotted together on the axes.

The next component of the M-file plots the input data, using Handle Graphics methods to set properties of the line object, the axes, and the legend that mimic the plot in Curve Fitting Tool:

% --- Plot data originally in dataset "pop vs. cdate"
cdate = cdate(:);
pop = pop(:);
h_ = line(cdate,pop,'Parent',ax_,'Color',[0.333333 0 0.666667],...
     'LineStyle','none', 'LineWidth',1,...
     'Marker','.', 'MarkerSize',12);
xlim_(1) = min(xlim_(1),min(cdate));
xlim_(2) = max(xlim_(2),max(cdate));
legh_(end+1) = h_;
legt_{end+1} = 'pop vs. cdate';

The next component "nudges" the x-axis limits, leaving a space of 1% of the x data range between the data and the vertical axes. This gives a tight plot, while preventing data from being plotted directly onto the vertical axes, where it would be difficult to see.

% Nudge axis limits beyond data limits
if all(isfinite(xlim_))
   xlim_ = xlim_ + [-1 1] * 0.01 * diff(xlim_);
   set(ax_,'XLim',xlim_)
else
    set(ax_, 'XLim',[1788, 1992]);
end

After all of the preliminaries, the M-file gets down to the business of fitting the data. The next component of the M-file uses fitoptions and fittype to create a fit options structure fo_ and a fittype object ft_ that encapsulate, respectively, information on the fitting method and the model. The inputs to fitoptions and fittype are read from the Fitting GUI in Curve Fitting Tool.

% --- Create fit "fit 1"
ok_ = isfinite(cdate) & isfinite(pop);
if ~all( ok_ )
    warning( 'GenerateMFile:IgnoringNansAndInfs', ...
        'Ignoring NaNs and Infs in data' );
end
st_ = [0.51510504095942344 0.35210694524343056 ];
ft_ = fittype('a*(x-b)^3',...
     'dependent',{'y'},'independent',{'x'},...
     'coefficients',{'a', 'b'});

The fit method is then called to fit the predefined fit type to the input data. Note that NaNs are removed from the data before the fit, using the logical vector ok_ defined in the previous component.

% Fit this model using new data
cf_ = fit(cdate(ok_),pop(ok_),ft_,'Startpoint',st_);

The next component of the M-file is a little obscure, since it uses a conditional with a guard condition that is always false (0). This code is generated intentionally, to give you the option of plotting the new input data against a fit based on the old data (the data that was originally imported into Curve Fitting Tool). To do so, simply change the 0 to true. The modified M-file then uses the cfit method to set the coefficients of the cfit object cf_ to the stored values computed with the old data. If you do not wish to do this, leave this component of the M-file alone, or delete it.

% Or use coefficients from the original fit:
if 0
   cv_ = { 1.3594203554767276e-005, 1724.6959436137356};
   cf_ = cfit(ft_,cv_{:});
end

With the fitting complete, the M-file calls the plot method to plot the cfit object cf_. Note that plot is called with the default plot type 'fit' (data and fit), but is also passed a confidence level of 0.95. To use this confidence level to plot prediction bounds for the fit or for new observations, change 'fit' to 'predfunc' or 'predobs', respectively. The rest of the code in this component of the M-file is more Handle Graphics, along the lines of previous components, setting Handle Graphics object properties that mimic the plot of the fit in Curve Fitting Tool.

% Plot this fit
h_ = plot(cf_,'fit',0.95);
legend off;  % turn off legend from plot method call
set(h_(1),'Color',[1 0 0],...
     'LineStyle','-', 'LineWidth',2,...
     'Marker','none', 'MarkerSize',6);
legh_(end+1) = h_(1);
legt_{end+1} = 'fit 1';

Finally, the M-file takes care of "loose ends": hold is toggled off to its default behavior, the legend is positioned, and the x and y labels ('x' and 'y' by default) are removed.

% Done plotting data and fits.  Now finish up loose ends.
hold off;
leginfo_ = {'Orientation', 'vertical', 'Location', 'NorthEast'}; 
h_ = legend(ax_,legh_,legt_,leginfo_{:});  % create legend
set(h_,'Interpreter','none');
xlabel(ax_,'');               % remove x label
ylabel(ax_,'');               % remove y label

Modifying the Code

With an understanding of the components of the generated M-file, it is easy to modify the code to produce a customized curve fit and display. The basic structure of the M-file is already in place for you, and you can concentrate on the details that interest you most.

A natural modification of the M-file would be to edit the function declaration at the top of the file to return the cfit object cf_ created by the fit, as follows:

function cf_ = myfit2(cdate,pop)

Note the change in the function name from myfit to myfit2. The modified M-file should then be saved to a file named myfit2.m.

You might also want to return goodness-of-fit statistics, which the M-file, by default, does not compute. You would have to modify both the call to fit:

[cf_,gof] = fit(cdate(ok_),pop(ok_),ft_,fo_);

and the function declaration:

function [cf_,gof] = myfit2(cdate,pop)

You might also want to alter the call to plot, say to show prediction intervals for new observations:

h_ = plot(cf_,'predobs',0.95);

Running the M-file with the above modifications on the new data from Running the Generated M-file produces the following output to the command line:

[c,g] = myfit2(cdate,newpop)
c =
     General model:
       c(x) = a*(x-b)^3
     Coefficients (with 95% confidence bounds):
       a =  7.211e-006  (-2.389e-006, 1.681e-005)
       b =        1670  (1548, 1792)
g = 
           sse: 5.5691e+004
       rsquare: 0.6561
           dfe: 19
    adjrsquare: 0.6380
          rmse: 54.1398

and the following display:

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2009- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS