To create a fitting function in MATLAB, you write a function that returns a parameter vector and accepts the independent variable as its first input, in that order. That signature is the key requirement; everything else, from least-squares methods to splines to custom equations, flows from how you build that function. You then pass a handle to it into fit, nlinfit, lsqcurvefit, or the Curve Fitter app. The rest of this guide walks through every stage: choosing the model, writing and testing the function, matching initial guesses, comparing candidates fairly, and diagnosing the failures that produce warning-laden or meaningless fits.
The advice below reflects stable MATLAB behavior across recent releases. If your version differs, the same principles apply, but verify specific function names and options in your installation's documentation.
The three commitments a MATLAB fitting function must honor
MATLAB's fitting tools all assume a common contract. Break it and you'll get cryptic errors or silent garbage.
First, input order matters. Every solver passes the independent variable first and the parameters second. nlinfit(X,Y,fun,beta0) calls fun(X,beta0), and lsqcurvefit(fun,x0,X,Y) calls fun(x0,X), so if you split the model into a separate file you must respect whichever solver you target. The anonymous-function form avoids the confusion entirely: @(p,x) p(1)*exp(-p(2)*x) matches nlinfit order (parameters first), and the fit function uses a slightly different convention we'll cover below.
Second, the function returns one output — a vector or array of predicted values the same size as the dependent data. If your data is column-oriented, the model output should be too, or fit and nlinfit may complain about size mismatches.
Third, parameters must be real, finite, and identifiable. A model with two parameters that only ever appear as a product is not a two-parameter model; the solver will wander across a ridge of equally good solutions and return arbitrary values with inflated confidence intervals.
Here's the minimal pattern, an exponential decay in anonymous form:
That's the whole skeleton. The following sections fill in the decisions behind each line.
Choose the model before you write code
The fitting function is a translation of a model. Getting the model right is most of the work.
Start with the question the fit must answer. Are you estimating a physical rate constant? Then the functional form should come from the mechanism, and the parameters should carry units. Are you smoothing and interpolating? Then a spline or a low-order polynomial is appropriate, and interpretability matters less. Are you screening many candidate shapes? Then plan for comparison across models from the start.
Three broad families cover most work:
Parametric models with a fixed equation: exponential decay, Michaelis–Menten, Gaussian peaks, logistic growth. You get interpretable parameters and confidence intervals, but the form must be defensible. Polynomials and rational functions: convenient, but high-degree polynomials oscillate wildly outside the data range and can produce numerically unstable coefficient estimates. A degree-7 polynomial fit is a red flag in most real analyses. Smoothers and splines: fit supports 'smoothingspline', 'cubicinterp', and related types without you writing a parameterized function at all. Use these when you need a curve, not a model.
Write the equation down on paper first, with parameter meanings and expected magnitudes. That single habit prevents most of the debugging in later sections, because you'll know whether a returned rate constant of 4,000 per second is a solver failure or a discovery.
Write the fitting function in one of three forms
MATLAB accepts three practical forms, and the right one depends on whether you need reusability, parameters, or speed.
Anonymous function — best for short equations used in one script:
Use it when the expression fits on one line and you don't need to reuse it across files. For fit, the parameter vector is the first argument and the data second, which matches the pattern above.
Local function at the end of a script (supported in scripts since R2016b) — best for multi-line models or models with branching:
Pass it as @double_exp to the solver. Keep it in the same file while iterating; move it to its own file named double_exp.m only when other scripts need it.
Separate function file — appropriate for shared models or when the function is long. Same signature, but now the function name must match the filename.
One subtlety with fit: the library models use a different convention, and custom models passed to fit may take the coefficient vector first, as shown. If you're calling fit and get a dimension error on the first evaluation, swap the argument order in your function and test again — this is the single most common beginner mistake.
Test the function before fitting anything:
If it plots sensibly or returns a plausible vector, the signature and arithmetic are sound. If it errors, you've isolated the problem to the function rather than the solver.
Set initial guesses and bounds that give the solver a chance
Nonlinear least squares is local. The starting point b0 determines which minimum you reach, and a bad start can produce a converged fit to nonsense.
Three practical rules:
Scale your start to the data. If the response runs from 100 to 10, a decay amplitude near 90 and a baseline near 10 is a sane start. Guessing 1 and 1 for those parameters may still converge, but slowly and sometimes to the wrong basin.
Bound the parameters you know something about. fit accepts 'Lower' and 'Upper' vectors; lsqcurvefit takes lb and ub. Bounds expressing physical reality — a rate constant that must be positive, a mixing fraction between 0 and 1 — reduce spurious solutions and make the optimizer more robust. Bounds are not a substitute for a good start, but they catch sign errors.
Estimate start values from the data where possible. The peak height of the data approximates an amplitude, the final plateau approximates a baseline, and the time to fall to 37 percent of the initial value approximates a time constant. These crude readings are usually within an order of magnitude, which is enough.
For linear-in-parameters models — polynomials, sums of fixed basis functions — you don't need starts at all: polyfit and the backslash operator solve the least-squares problem directly. Reserve iterative fitting for genuinely nonlinear equations.
Run and inspect the fit before trusting it
A converged fit is not necessarily a correct fit. fit returns a cfit object and, by default, no error; you have to look.
Plot the data and the fitted curve on the same axes. Residual structure is the fastest diagnostic: leftover curvature means the model is too stiff, a fan-shaped residual pattern suggests non-constant variance, and a single large residual points to an outlier or a data-entry error.
Then read the fit object's statistics:
Report the 95 percent confidence intervals alongside the coefficients. Wide intervals relative to the estimate mean the parameter is poorly determined by this data — often because the model has redundant parameters. For example, a single exponential plus offset fitted to data covering less than one time constant will give a rate constant with an enormous interval, because the data barely constrains it.
Check the goodness-of-fit measures with appropriate skepticism. R-squared always rises when you add parameters, so compare adjusted R-squared or information criteria like AIC when choosing among models.
Compare candidate models on equal footing
When two functional forms are plausible, the comparison must hold the data and the error assumption fixed.
Fit both models to the identical data points, with the same weighting, and then compare adjusted R-squared, AIC, or cross-validated error. AIC penalizes parameter count; adjusted R-squared does something similar for linear models. Neither is meaningful if the two fits used different subsets, different weights, or different outlier handling.
| Criterion | What it rewards | Main caution |
|---|---|---|
| R-squared | Variance explained | Always improves with extra parameters |
| Adjusted R-squared | Variance explained per parameter | Assumes linear model structure |
| AIC | Fit with a complexity penalty | Requires comparable likelihood assumptions |
| RMSE on held-out data | Predictive accuracy | Needs enough data to split |
For small datasets, fit both models and compare confidence intervals on the parameters that carry scientific meaning. If the extra parameters of the richer model have intervals spanning zero, the simpler model is often the right report.
A worked example makes the comparison concrete. Suppose 40 measurements of a decaying signal span two time constants. A single exponential gives an adjusted R-squared of 0.94 with a residual pattern showing systematic curvature; a double exponential raises it to 0.997, and both decay rates have tight confidence intervals of roughly plus or minus 8 percent. Here the richer model is justified. The same comparison on 12 noisy points spanning half a time constant would not justify it — the second rate would have an interval spanning an order of magnitude, and you'd report the simpler model with a note about the limited range.
Use the Curve Fitter app for custom equations, then export
The Curve Fitter app (cftool) is a legitimate way to create and validate a custom fitting function without writing solver calls.
The workflow: open cftool, select X and Y data from the workspace, choose Custom Equation, type the equation using x as the independent variable and coefficients named as you like, and edit the start points and bounds in the fit options panel. The app plots residuals and reports coefficients with confidence bounds immediately.
The app's real payoff is the export. Use Fit > Save to Workspace to get the cfit object and the goodness-of-fit structure, or Generate Code to produce a function that reproduces the fit programmatically. That generated function is often the cleanest starting point for a scripted analysis, because it encodes the exact options that worked interactively.
Two limits worth knowing: the app is ideal for exploration but not for automated pipelines, and equations entered in the app must follow its coefficient-naming convention, so complex multi-line models are often easier to develop as a function file first.
Troubleshoot the common fitting failures
Most fitting problems fall into a few recognizable patterns.
"Inf or NaN computed" or the solver stalls immediately. Your function returns non-finite values at the start point — often a log or square root of a negative number, or a division by zero. Test the function at b0 directly and fix the domain issue, or add bounds that keep parameters in the valid region.
Fit converges to a flat line or absurd parameters. Usually a poor start point, redundant parameters, or unnormalized data. Try rescaling the independent variable (for instance, fit against time in hours rather than seconds) and reseeding the start from data features.
Warning about ill-conditioned Jacobian. Parameters are correlated or the model is over-parameterized for this data. Check the confidence intervals; if several are enormous, simplify the model.
Fit looks fine but predictions outside the data range are wild. Polynomials, rational functions, and unconstrained exponentials extrapolate badly by nature. If extrapolation matters, choose a model grounded in the mechanism, and report predictions with uncertainty rather than as point values.
If a fit repeatedly fails for reasons you can't diagnose after checking the function, the start point, and the bounds, the model may simply be wrong for the data. That's a signal to revisit the model rather than to keep tuning the solver.
A sensible stopping point: when residuals show structure that no defensible model removes, when parameters remain unidentifiable after reasonable standardization, or when the analysis carries safety or regulatory consequences, hand the problem to someone with statistical expertise rather than accepting a converged but questionable result.
Why the function-based approach beats dragging a curve
The point of writing an explicit fitting function is that it makes every assumption visible. The equation, the parameter order, the start points, and the bounds are all in the code, so a colleague can audit the fit and a future version of you can reproduce it.
That matters more than speed. Anonymous functions and local functions run through the same optimizers as the built-in library models, and for problems of ordinary size the difference is negligible. What you gain is control: custom equations the library doesn't include, parameter constraints from the physics, and a record of the choices that produced the reported numbers.
A short checklist before you report any fit: the function was tested at the start point, the fit object's confidence intervals were inspected, residuals were plotted, the model comparison used identical data and weighting, and the coefficients are reported with units and intervals. Meet those conditions, and the MATLAB side of curve fitting stops being a source of surprises and becomes a tool you can defend.