% Find midranks for data in a column
% Input: ww = Nxr matrix
% Output: [midr tiegr] = getmidranks(ww)  where
%   midr  are midranks determined by data in first column of ww
%   tiegr  lists the tiegroup sizes with tsize >= 2
%          (tiegr(i)=0 for i > ntg = number of such tie groups)

function [midr tiegr] = getmidranks(ww)
  %% Number of rows of ww
  nn=size(ww,1);
  %% Set zz = [first column of ww   then   1:nn]
  zz=[ww(:,1) (1:nn)'];  %'
  zz=sortrows(zz,1);    % Sort rows by first column
  midr=(1:nn)';         %' Default for midranks of sorted data
  %% Using column 1 of zz, assign midranks and tie groups
  oldval=zz(1,1)-10;  firsti=-1;  tsize=-1;
  %% Since zz(i,j) is sorted, all other zz(i,1) > oldval
  g=0;  tiegr=zeros(nn,1);
  for i=1:nn;
    if zz(i,1)==oldval tsize=tsize+1;
    else 
       % End of previous tie group if tsize>0
       % Copy midranks of tie group to midr()
       % If tsize==1, midr(firsti) is already firsti
       if tsize>1 g=g+1;  tiegr(g)=tsize;  mr=(firsti+i-1)/2;
         for j=firsti:i-1;  midr(j)=mr;  end;  end;
       % Initialize for next tie group
       tsize=1;  oldval=zz(i,1);  firsti=i;  end;
    end;
  %% Repeat code for possible last tie group
  %% Last element of last tiegroup is nn, not nn-1
  if tsize>1 g=g+1;  tiegr(g)=tsize;  mr=(firsti+nn)/2;
    for j=firsti:nn;  midr(j)=mr;  end;  end;
  %% Re-sort midranks on original-ordinal column
  zz1 = [zz(:,2)  midr];
  zz1 = sortrows(zz1,1);
  midr = zz1(:,2);

  
  

