Tutorial · Intermediate · 12 min
Fitting data for a paper
Simulate measurements, fit a model, show uncertainty and residuals, and report the numbers.
Reproducible "measurements"
rng(seed)makes random numbers repeatable, so your figure is the same every time.
Try it ↗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')Fit a straight line
polyfit(x, y, 1)returns slope and intercept;polyvalevaluates the fitted line.
Try it ↗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)))Error bars and residuals
errorbarshows uncertainty; a secondsubplotshows what the model misses.
Try it ↗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')Report the numbers
Compute statistics and print them with
fprintf. Then export the figure as SVG and the data as CSV.
Try it ↗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))slope 2.040 intercept -0.218 RMS error 0.871 r 0.9626