%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% FUNCTION LOG_LIKELIHOOD_NORMAL
% 
% This function computes the log-likelihood of the Normal distribution with
% parameters mu and sigma.
%
% INPUT: beta - Optimization values for the parameters
%               data - Normal data.
% 
% OUTPUT: Log-Likelihood value for the Normal.
%
%                                                   César Zamudio 9.16.2013
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%The statement below commences to define a function. Leave the f and the
%obj, and define whatever parameters you need here.

%Note that the parameters in the main script and the parameters here do not
%need to have the same name. For example, in the script Main_LL_Normal, the
%parameters are called x, while here they're called beta.

function f=obj(beta,DATA)
%EXTRACT parameters from the beta vector
mu=beta(1,1);
%Notice how we will not take the square of sigma. This can lead to
%computation errors. Simply define "sigma2" as your PARAMETER OF INTEREST.
sigma2=beta(2,1);

%Sample size
N=size(DATA,1);

%Initialize log-likelihood value
lik=0;

%%%%%%%%%%%%%%%%%%%%%%%%%
%ALGORITHM - Normal L.L.%
%%%%%%%%%%%%%%%%%%%%%%%%%

%LL_TERM1 is the first term of the log-likelihood
LL_TERM1=-(N/2)*(log(2*pi));
    
%LL_TERM2 is the second term. Notice how we use the SQUARE of sigma so it is always positive!
LL_TERM2=-(N/2)*(log(sigma2));
    
%LL_TERM 3 is the last term. Notice how we use only one data point because we're inside a for cycle.    
LL_TERM3=-(1/(2*sigma2))*sum((DATA-mu).^2);
    
%Update likelihood   
lik=LL_TERM1+LL_TERM2+LL_TERM3;

f=-lik;



