function H=chi2rayltest(x, alpha)
% CHI2RAYLTEST: Single sample Pearson Chi Square goodness-of-fit statistical test to examine
% a null hypothesis of Rayleigh Channel.
% H=CHI2RAYLTEST(X,ALPHA) performs the particular case of Pearson Chi Square
% test to determine whether the null hypothesis of a Rayleigh channel realization is
% a reasonable assumption regarding the population distribution of a complex random sample X
% with the desired significance level ALPHA.
%
% H indicates the result of the hypothesis test according to the MATLAB rules
% of conditional statements:
% H=1 => Do not reject the null hypothesis at significance level ALPHA.
% H=0 => Reject the null hypothesis at significance level ALPHA.
%
% The Chi Square hypotheses and test statistic in this particular case are:
%
% Null Hypothesis: X is a base-band Rayleigh channel realization with
% unknown mean and variance.
% Alternative Hypothesis: X is not a Rayleigh channel realization.
%
% The complex random sample X is shifted by its estimated mean and normalized by its
% estimated standard deviation giving Rayleigh parameter b=1/sqrt(2).
% The test drops K factor of Rician distribution for K > -inf[dB], therefore the random sample
% from a Rician channel realization will pass the test as well.
% The tested bins XP are chosen to give 10 tested bins with equal expected probability. These bins
% supply a sufficient statistic for LENGTH(X)>=100.
%
% Let E(x) be the expected frequency X falls within XP according to the Rayleigh
% distribution and O(x) be the observed frequency. The Pearson statistic,
% X2=SUM((E(x)-O(x))^2/E(x)) distributes Chi Square with length(XP)-2 degrees
% of freedom.
%
% The decision to reject the null hypothesis is taken when the P value (probability that Chi2
% random value with length(XP)-2 degrees of freedom is greater than X2) is less than
% significance level ALPHA.
%
% X must be a complex row vector representing a random sample corresponding to a base-band
% channel realization. ALPHA must be a scalar.
% The function doesn't check the formats of X and ALPHA, as well as a number of the
% input and output parameters.
%
% Author: G. Levin, June, 2003.
%
% References:
% W. T. Eadie, D. Drijard, F. E. James, M Roos and B. Sadoulet, "Statistical Methods
% in Experimental Physics", North-Holland, Sec. Reprint, 1982.
%Normalize x
N=length(x);
x=(x-mean(x))/std(x); %standardization
xp=[0, 0.3246, 0.4724, 0.5972, 0.7147, 0.8326, 0.9572, ...
1.0973, 1.2686, 1.5174, inf]; %tested bins
E=N*diff(-exp(-xp.^2)); %Rayleigh CCDF
S=histc(abs(x), xp);
O=S(1:end-1); %%observed frequency
%plot(xp(2:end),E,'k-',xp(2:end),O,'k.');
x2=sum((E-O).^2./E); %statistics
pval=1-gammainc(x2/2,(length(O)-2)/2); %p value
H=(pval>=alpha);