Ron Bakker/MathLabHelp
Open MathLab ↗

Tutorial · Intermediate · 12 min

Fitting data for a paper

Simulate measurements, fit a model, show uncertainty and residuals, and report the numbers.

  1. Reproducible "measurements"

    rng(seed) makes random numbers repeatable, so your figure is the same every time.

    rng(42)
    x = linspace(0, 5, 20);
    y = 1.8*x + 0.5 + 0.7*randn(size(x));
    scatter(x, y, 40, 'filled')
    title('measurements')
    Try it ↗
  2. Fit a straight line

    polyfit(x, y, 1) returns slope and intercept; polyval evaluates the fitted line.

    rng(42)
    x = linspace(0, 5, 20);
    y = 1.8*x + 0.5 + 0.7*randn(size(x));
    p = polyfit(x, y, 1);
    scatter(x, y, 40, 'filled'), hold on
    plot(x, polyval(p, x), 'LineWidth', 2), hold off
    legend('data', sprintf('fit: %.2f x + %.2f', p(1), p(2)))
    Try it ↗
  3. Error bars and residuals

    errorbar shows uncertainty; a second subplot shows what the model misses.

    rng(42)
    x = linspace(0, 5, 20);
    y = 1.8*x + 0.5 + 0.7*randn(size(x));
    p = polyfit(x, y, 1);
    subplot(2, 1, 1)
    errorbar(x, y, 0.7*ones(size(x)), 'o'), hold on
    plot(x, polyval(p, x), 'LineWidth', 2), hold off
    title('linear fit ± 1σ')
    subplot(2, 1, 2)
    stem(x, y - polyval(p, x)), yline(0, 'k:')
    title('residuals')
    Try it ↗
  4. Report the numbers

    Compute statistics and print them with fprintf. Then export the figure as SVG and the data as CSV.

    rng(42)
    x = linspace(0, 5, 20);
    y = 1.8*x + 0.5 + 0.7*randn(size(x));
    p = polyfit(x, y, 1);
    r = y - polyval(p, x);
    R = corrcoef(x, y);
    fprintf('slope      %.3f\n', p(1))
    fprintf('intercept  %.3f\n', p(2))
    fprintf('RMS error  %.3f\n', sqrt(mean(r.^2)))
    fprintf('r          %.4f\n', R(1, 2))
    Try it ↗
    slope      2.040
    intercept  -0.218
    RMS error  0.871
    r          0.9626