function [H , pval, aver1 ] = kruskalwallistest(data, belong)
% ------------------------------------------------------------------------------------
%   KRUSKAL-WALLIS TEST
%   Input:  data - samples concatenated together, data vector. 
%           belong - treatment groups for elements in the data vector;
%   
%   Output: H - Kruskal Wallis statistic;
%           p - p-value for testing equality of distributions (equality of locations)
%           aver1 -- average ranks per treatment,  1/n_i
%           sum_{j=1}^n_i (R^2(X_ij))
%   Example of use:
%  
%  >> data  =  [ 1 3 4  3 4 5  4 4 4 6 5 ];
%  >> belong = [ 1 1 1  2 2 2  3 3 3 3 3 ]; 
%  >> [H, p, aver1] = kruskalwallistest(data, belong)
%
% H = 3.8923
% p = 0.1428
% aver1 = [3.1667   6    7.7]
%   Comes with functions ranks.m, tie.m, and different.m  
%-------------------------------------------------------------------------------------
% Copyright (C) 2002 by GaTech
% Ver 0.1   9/28/2002
% Ver 0.2  12/5/2013
% Ver 0.3   4/5/2014
data = data(:)';      
  n = length( data );   
belong = belong(:)' ;      
  N = length( belong ); 
  if n ~= N 
      error('DATA and BELONG should be paired.')
  end
  Ra = ranks(data, 1);
  di = different(belong);
  k = length(di);
  ni=[];
 for i = 1:k
      ni= [ni sum( belong==di(i) ) ];
 end
  aver1 = [];   aver2 = [];  
  for i = 1:k
      aver1= [aver1   sum(Ra(belong==di(i)))/ni(i)];
      aver2= [aver2   sum(Ra(belong==di(i)))^2/ni(i)];
  end
S2= 1/(n-1) * (sum(Ra.^2) - 1/4*n*(n+1)^2);
Ti = sum(aver2);
H = 1/S2 * ( Ti -  1/4 * n*(n+1)^2);
pval = 1-chi2cdf(H, k-1);
figure;
errorbar( aver1,    tinv(0.975,n-k)  .*  sqrt(S2)./sqrt(ni))
%------------------------------------------------------------------------------------
 function a = different(x)
 %
 % returns only different elements of x
 %
  if any (isnan (x))
    a = NaN;
  else
  a = [];
  x = x(:);
  s = sort(x);
  a = [s([1; find(s(2:end) > s(1:end-1)) + 1]); a];
  end
  %-------------
function  r = ranks(data, glob)
%--------------------------------------------------------------------
% right and also from right to left, and then averaged!
%---------------------------------------------------------------------
if nargin < 2
    glob = 1;
end
    shape = size(data);
if glob == 1    
     data=data(:);
 end     
% Ties ranked from UptoDown
  [ irrelevant , indud ]  =  sort(data);
  [ irrelevant , rUD ]    =  sort(indud);
% Ties ranked from RtoL
  [ irrelevant , inddu ]  =  sort(flipud(data));
  [ irrelevant , rDU ]    =  sort(inddu);
% Averages ranks of ties, keeping ranks of no-tie-observations the same
r = (rUD + flipud(rDU))./2;
r = reshape(r,shape); 
%---------------------------------------------------------------------
% Copyright (C) 2002 by GaTech
% Ver 0.1   9/28/2002