To plot a fitted function in MATLAB, create or fit a model, generate a dense set of x-values across the data range, evaluate the model at those points, and draw both the fitted curve and the original data on the same axes. The key condition is that your evaluation grid must cover the actual range of your data—not a generic 0-to-1 default—or the curve will appear truncated or extend into regions where the fit wasn't validated. The exact commands differ slightly depending on whether you use fit from the Curve Fitting Toolbox, polyfit/polyval from base MATLAB, or a custom anonymous function, but the underlying sequence is the same in every case.

This guide walks through each approach, shows how to check that the plot is telling the truth, and covers the failure modes that produce curves that look right but aren't.

The universal recipe: what every fitted-function plot needs

Every fitted-function plot consists of four ingredients. Once you internalize these, any specific syntax is just details.

First, a model—either a set of coefficients (polyfit), a fitted object (fit), or a function handle you defined yourself. Second, an evaluation grid: a vector of x-values where you'll compute the model's output. Third, the evaluated response, typically yfit = model(xgrid). Fourth, a plotting call that overlays the curve on the raw data, usually hold on plus a plot command.

The most common beginner error is skipping the grid step and trying to plot the model's parameters directly, which produces a straight line through two points or a meaningless bar chart. A fitted function is a function—it needs inputs to produce outputs, and those inputs must be chosen deliberately.

Prerequisites are minimal: a MATLAB installation (base MATLAB suffices for polyfit; the Curve Fitting Toolbox is needed for fit), your data as column vectors x and y of equal length, and a rough idea of the functional form you expect. If your x-values are unsorted, sort them first with [x, idx] = sort(x); y = y(idx); to avoid a zigzagging "curve."

Approach 1: Polynomial fitting with polyfit and polyval

This is the base-MATLAB path and the right choice for quick polynomial fits without toolboxes.

Start by fitting: p = polyfit(x, y, n); where n is the polynomial degree. A degree-1 fit is a line, degree-2 a parabola, and so on. Then build a grid: xgrid = linspace(min(x), max(x), 200); — 200 points is usually enough for a smooth curve on screen, and you can raise it if the curve looks angular. Evaluate with yfit = polyval(p, xgrid); and plot.

A complete working example with synthetic data:

Two details in that example matter. The randn term adds noise so the fit is a genuine approximation rather than an interpolation, which is what you'd face with real measurements. And the sprintf in the legend displays the coefficients so the reader knows what the curve represents—without that, a red line on a plot conveys almost nothing.

Choose the grid via min(x) and max(x) rather than hardcoding numbers. If your data runs from 0.003 to 0.087 (say, small concentrations), a hardcoded linspace(0, 1, 200) will compress all the interesting behavior into a sliver of the axis. This single habit prevents most bad fitted-function plots.

Approach 2: The fit function from the Curve Fitting Toolbox

When you need exponential, Fourier, Gaussian, or spline models, fit is more expressive than polyfit. It returns a cfit object that behaves like a function.

The syntax is f = fit(x, y, 'exp1'); (or 'poly3', 'gaussian1', 'smoothingspline', and many others). Evaluate the object directly: yfit = f(xgrid);. The plotting is otherwise identical to the polynomial case.

That plot(f, x, y) overload is convenient and handles the grid for you, but it's worth knowing the manual version because you'll often want to customize the grid, add confidence bands, or overlay multiple fits. To inspect goodness of fit before plotting, f displays coefficients and the R-squared value when printed—checking this first is cheap and tells you whether the model form is even plausible.

One subtlety: fit with the default options minimizes squared error over the raw data. With noisy data and a flexible model (like a high-order polynomial or a smoothing spline), the curve can chase noise. Plotting will reveal this as oscillation between data points. If you see that, reduce model flexibility, not the number of evaluation points—the grid density isn't the problem.

Approach 3: Plotting a custom or anonymous function

Sometimes you've derived a model analytically or obtained parameters from elsewhere and just need to visualize it. In that case, define a function handle and compose it with your grid.

This works for any function handle, including one that wraps a fitted object: model = @(x) f(x) + offset; if you need an adjustment after fitting. Anonymous functions impose no toolbox requirement and are the cleanest option for demonstrations, teaching, or when the fit was done in another environment entirely.

For parametric families where you want several curves on one plot (different decay constants, say), loop over the parameters and call hold on once before the loop. That lets you compare shapes without duplicating code.

Checking that your plot is correct

A fitted-function plot can be wrong in ways that aren't visually obvious, so a few cheap checks are worth running every time.

Check the residual behavior. Compute resid = y - f(x); (or y - polyval(p, x)) and plot it in a second subplot. A fit whose residuals show a clear trend—a U-shape for a linear fit through curved data—means the model form is wrong, no matter how good the main plot looks. A residual plot centered on zero with no pattern supports the fit.

Confirm the grid endpoints. Print [min(xgrid), max(xgrid)] and compare to your data range. If they disagree, you've plotted an extrapolation or truncated the curve.

Verify evaluation isn't extrapolating dangerously. If you deliberately extend xgrid beyond the data to show the trend continuing, mark the data region (with xline at the boundaries, for instance) so viewers understand which part of the curve is unsupported. Extrapolated polynomial fits can swing wildly just outside the data range, and a plot that doesn't signal this is misleading.

Re-plot with a denser grid if the curve looks segmented. Angularity at 50 points usually disappears at 300. If it doesn't, the underlying function genuinely has sharp features and the plot is telling the truth.

Common failures and how to diagnose them

A handful of problems account for most broken fitted-function plots.

The error message "Vectors must be the same length" almost always means you plotted xgrid against y or x against yfit—mismatched pairings. Every plot(a, b) call needs a and b to be the same size, and the common slip is mixing your data vector with your evaluation vector.

A curve that appears as a single point or a vertical spike usually means the grid has only one or two elements, often because min(x) and max(x) are equal (e.g., you passed a scalar by mistake or filtered the data down to one sample). Print size(xgrid) to confirm.

A curve that's invisible despite being plotted often sits outside the axis limits because of an outlier in the data that stretched the axes, or because the fit diverged. Try axis auto after plotting, or inspect [min(yfit), max(yfit)] to see whether the fitted values are sane.

If fit returns a warning about poor convergence or a fit with huge uncertainty, the model form likely doesn't match the data. Rather than plotting a bad fit more attractively, revisit the model choice—a 'gaussian1' won't describe a monotonic decay, and no amount of plotting polish fixes that.

When the data include NaN values, polyfit will return NaN coefficients and the plot will be empty. Filter first: valid = ~isnan(x) & ~isnan(y); x = x(valid); y = y(valid);.

Making the plot communicate: legends, axis limits, and multiple fits

Once the mechanics work, the plot's job is to communicate. Three habits carry most of the weight.

Build legend labels programmatically with sprintf so coefficients or model names appear automatically; hand-typed legends drift out of sync when you refit. Set axis limits with xlim and ylim deliberately rather than relying on axis auto, especially when overlaying fits—auto-scaling can make a good fit look poor by zooming to an outlier. And when comparing two model forms (linear versus quadratic, say), plot both fits on the same axes with distinct colors and include the residual plot as a second subplot; the comparison is then visible rather than asserted.

For publication-quality output, exportgraphics(gcf, 'fit.png', 'Resolution', 300) produces a high-resolution raster, while print(gcf, 'fit.eps', '-depsc') gives vector output that scales cleanly in print. The fitted curve's LineWidth should generally exceed the data markers' visual weight—typically 1.5 to 2 points for the curve—so the model reads as the primary element.

A worked estimate: how many grid points do you need?

The grid density question has a practical answer rather than a theoretical one. For a smooth function displayed at roughly 1,000 pixels wide, 200 to 500 evaluation points make curvature indistinguishable from a true continuous curve. Below about 100 points, high-curvature regions (peaks, steep exponentials) show visible faceting.

For a concrete case: plotting an exponential decay with time constant 0.5 over a range of 0 to 5 means the function drops to about 0.7% of its initial value by the end. With 100 points across that range, the spacing is 0.05 time units—a tenth of the time constant—which renders the knee of the curve smoothly. With 20 points, spacing is 0.25, half a time constant, and the curve will look polygonal near the bend. So 100 to 200 points covers most single-decay cases comfortably; if in doubt, plot at 500 and check whether anything changes.

The cost is negligible: evaluating a model at 500 points is instantaneous on any modern machine, so there's little reason to be stingy. The real constraint is interpretability, not computation.

When to bring in a professional or step back

These plotting steps are self-contained and low-risk, but two situations warrant caution. If you're fitting a model whose parameters carry physical, clinical, or financial meaning—a pharmacokinetic decay constant, a risk model—the plotting is the easy part; validating that the functional form is appropriate and that extrapolation is defensible needs domain expertise, and a clean plot can create false confidence. And if fit reports non-convergence or wildly wide confidence bounds that you can't resolve by simplifying the model, the data may not support the fit you're attempting.

For anything where the fitted parameters feed into a downstream decision, treat the plot as a diagnostic, not a verdict, and have someone qualified review both the model choice and the residuals before the numbers travel further.

FAQ

Can I plot a fit without the Curve Fitting Toolbox? Yes—polyfit and polyval are in base MATLAB and handle polynomial fits. For non-polynomial forms, define an anonymous function with your own coefficients, or use fminsearch to estimate parameters and then plot the resulting handle.

Why does my fitted curve stop short of the data's right edge? Almost always because xgrid was built from hardcoded limits smaller than max(x). Rebuild it with linspace(min(x), max(x), N).

How do I show confidence bounds around a fitted curve? With a cfit object from fit, the predint function returns prediction intervals at your grid points; plot the lower and upper bounds as dashed lines around the fitted curve. Base-MATLAB polynomial fits don't provide this automatically.

The curve looks jagged—should I increase grid points? Try it first, since it's free, but if the jaggedness persists at 500+ points, the model itself is oscillating (common with high-degree polynomials or smoothing splines on noisy data), and the fix is a simpler model, not a denser grid.