%% Statistics of Some Data

clear all, load gas.mat
price2
clf, hist(price2)
n = length(price2)
mu = mean (price2)
sigma = std(price2) * sqrt((n-1)/n)

%
%% Fitting a Gaussian to the Data

x = min(price2) : 0.25 : max(price2);
y = normpdf(x, mu, sigma);
scaled_y = y * 4/max(y);
hold on
plot(x, scaled_y, 'r')

%
%% Calculating the Likelihood


mus = 116 : 0.5 : 121;
sigmas = 2.5 : 0.1 : 5.5;
[x,y] = meshgrid(mus, sigmas);
z = gauslike(x, y, price2);
clf, surfc(x, y, z*10)
xlabel mu
ylabel sigma
zlabel Likelihood
title('Likelihood of Parameters Given the Data')
rotate3d on
figure, hold on
[c,h] = contour(mus, sigmas, z * 1e24);
clabel(c,h)
xlabel mu
ylabel sigma
title('Likelihood x 1e24')
plot(mu, sigma,'rd')

%
%% Interactive Contour Plot

% fsurfht('gauslike', [116 122], [2.5 5.5], price2)

% gauslike must be defined in gauslike.m, not here.
% Click and drag to move the crosshairs
% Type the mean 118.5 into the X value box.
% Type the sigma value 3.6401 into the Y Value box. Note the Z value is 2.8386e-24.
% Compute std(price2) and type that value into the Y-value box. Note the Z value decreases.
% Conclusion: the peak likelihood is located at the sample mean, but not at the sample's standard deviation.
% Moral: the sigma value giving the greatest likelihood may not be the sample's sigma.
%

function z = gauslike(mu, sigma, points)
    n = length(points);
    z = ones(size(mu));
    for i = 1 : n
        z = z .* normpdf(points(i), mu, sigma);
    end
end