% Seed random number generator so results are reproducible
rng(12307)

% Generate function and measurements
x = linspace(0, 5, 1000);
y = exp(-x);
ym = y + 0.5*randn(size(x));

% Plot function and measurements
figure; hold on;
plot(x, y, 'k-');
plot(x, ym, 'b.');
legend('y = e^{-x}', 'y_m');
xlabel('x')
ylabel('y')
exportgraphics(gcf,'measurements.png')

% Set edges of bins
xe = 0:0.5:5;

% Calculate averages within each bin
[~,~,bin] = histcounts(x, xe);
xb = accumarray(bin', x, [], @mean);
yb = accumarray(bin', ym, [], @mean);

% Estimate remaining error in average y values
rms = accumarray(bin', ym, [], @std);
N = accumarray(bin', ones(size(ym)), [], @sum);
stderr = rms./sqrt(N);

% Plot binned data
figure; hold on;
plot(x, y, 'k-');
errorbar(xb, yb, stderr, 'b-o');
legend('y = e^{-x}', 'binned averages (width = 0.5)');
xlabel('x');
ylabel('y');
exportgraphics(gcf, 'binned.png')