function p = lyngby_test_wilrank(X, Y)

% lyngby_test_wilrank  - Wilcoxon sign rank test
%
%       function P = lyngby_test_wilrank(X)
%
%       Input:  X   Data points 
%               Y   Data points 
%
%       Output: p   p-value
%
%       Wilcoxon (Mann-Whitney) test (Wilcoxon matched pair signed
%       rank test).       
%
%       The test is mass-univariate performed independently over each
%       column.
%
%       Ref: Råde, Westergren (1990), BETA Matematics Handbook, p. 452
%            Conradsen, En introduktion til Statistik, 1B, p. 3.69
%
%       See also LYNGBY, LYNGBY_CDF_WILRANK, LYNGBY_TEST_FISHERSG.
%
% $Id: lyngby_test_wilrank.m,v 1.3 2003/08/07 16:43:24 fnielsen Exp $



    [rX, cX] = size(X);

    if nargin == 1
      Z = X; 
    else
      Z = X - Y;
    end
    S = sign(Z);
    [dummy, Itmp] = sort(abs(Z));
    [dummy, I] = sort(Itmp);
    R = S .* I;
 
    if 1 == 1
      % The Beta handbook method, page 452
      W = 0.5 * sum(R) + rX*(rX+1)/4;
    else
      % Knut Conradsen method
      W = zeros(1, cX);
      for c = 1:cX
	i = find(S(:,c) >0);
	W(1,c) = sum(I(i,c));
      end
    end

    for c = 1:cX
      p(1,c) = 1 - lyngby_cdf_wilrank(W(c), rX);
    end

