n = 500;  % Sample size

sig2 = 1; % Variance



% Generating the sample



aux = randn(2,n);

S = sqrt(sum(aux.^2));



% Histogram of the sample



figure(1)

hist(S,20)



% Estimating the parameters of the log-normal distribution



W = log(S);

w0 = (1/n)*sum(W);

WC = W - w0*ones(1,n);

gamma2 = (1/n)*WC*WC';



% Plotting the log-normal distribution with these parameters



t = linspace(eps,5,100);

pi_ln = exp(-1/(2*gamma2)*(log(t)-w0).^2)./t;

figure(1)

hold on

plot(t,50*pi_ln,'r-','LineWidth',2)

hold off



% Testing the log-normality: the sample W should be normal

% Move first the sample around the origin and scale so that the variance is

% a unity



WW = 1/sqrt(gamma2)*(W - w0);



figure(2)

hist(WW,20)



% Calculating the number of sample points within different credibility

% intervals



r = zeros(1,11);

r(11) = n;

for j = 2:10

    p = (j-1)/10;

    a = sqrt(2)*erfinv(p);

    r(j) = sum(abs(WW)<a);

end



r = (1/n)*r;

figure(3)

plot([0:10:100],r,'k.-','MarkerSize',20)



% Calculating the one-sided distributions: The sample points are divided in

% two, those to the left of the mean and those to the right, and the same

% analysis is done separately to both subsets. This test tells if there are

% significant asymmetries in the sample.



r_left = zeros(1,11);

r_right = zeros(1,11);

r_right(11) = n/2;

r_left(11) = n/2;

WW_left = WW(find(WW<0));

WW_right = WW(find(WW>0));

for j = 2:10

    p = (j-1)/10;

    a = sqrt(2)*erfinv(p);

    r_left(j) = sum(abs(WW_left)<a);

    r_right(j) = sum(WW_right<a);

end



r_right = (2/n)*r_right;

r_left = (2/n)*r_left;

figure(4)

plot([0:10:100],r_left,'k.-','MarkerSize',20)

hold on

plot([0:10:100],r_right,'r.-','MarkerSize',20)

legend('Left','Right','Location','NorthWest')

hold off



