%
% Simple example demonstrating why theory and practice are not the same when
% moving from pen and paper to computations on physical hardware. Different
% ways of computing the same quantity are equivalent on paper but not on
% hardware. Standard mean is computationally more efficient. The iterative
% approach is more robust.
%
function meanExample()
n = 5;
x = realmax/2 - 1;
x = x(ones(1,n))
fprintf('standard mean computation:');
mean(x)
fprintf('iterative mean computation:')
iterativeMean(x)
%
% Computing the mean iteratively can deal with larger values.
%
function m = iterativeMean(x)
n = size(x(:),1);
m = x(1);
for i=2:n
m = m*((i-1)/i) + x(i)/i;
end