%kruskal-wallis-test.m
%Kruskal-Wallis test 
c=10; 
n=round(rand(1,c)*45)+5;
AM=round(rand(1,c)*39)+1;
for i=1:1:c 
    Group{i}=randn(1,n(i))*5+AM(i);
    M{i}=mean(Group{i}); 
end
[P,Q]=sort(abs(cell2mat(Group)));
for i=1:1:length(P)
DATA(Q(i))=i;
end
Group=mat2cell(DATA,1,n); 
for i=1:1:c 
    M{i}=mean(Group{i});
end
%To check whether mean of the individual group are identical %using F-score 
m=mean(cell2mat(M));
SB=sum(n.*((cell2mat(M)-repmat(m,1,c)).^2)); 
SW=0; 
for i=1:1:c 
    SW=SW+sum((Group{i}-repmat(M{i},1,length (Group{i}))).^2);
end
VARSW=SW/(sum(n)-c);
VARSB=SB/(c-1);
F=VARSB/VARSW; 
%F follows F-distribution with order (c-1),(sum(n)-c) 
Y=fpdf(0:0.1:20,c-1,sum(n)-c); 
z=0:0.1:20; 
Z=cumsum(Y)/10;
figure
subplot(2,1,1) 
plot(z,Y,'r')
subplot(2,1,2)
plot(z,Z,'r')
%Locating 0.05 significant level (95% confident level) %is the value at which the cumulative distribution is %0.05 and 0.95 
[p1,q1]=find((Z-0.05)>0);
[p2,q2]=find((Z-0.95)>0);
hold on
plot([z(q1(1)) z(q1(1))],[0 Z(q1(1))],'-r*')
hold on
plot([z(q2(1)) z(q2(1))],[0 Z(q2(1))],'-r*')
plot(F,0,'bo')
%The Null Hypothesis is structured such that the %mean is equal to 90 %We reject the Hypothesis if F is greater than z(q1(1)) %or less than z(q2(1)) 
if((F<z(q1(1)))|(F>z(q2(1))))
    disp('Reject the Null Hypothesis (i.e., means are identical)')
else
    disp('Accept the Null Hypothesis (i.e., means are identical)')
end
figure
for i=1:1:c 
    plot(i*ones(1,n(i)),Group{i},'*')
    hold on 
end

