function  [d,beta] = xtab2dprime(distrib)

% XTAB2DPRIME -- Calculate d-prime from a joint S-R distribution
%
%  [d,beta] = xtab2dprime(distrib)
%
%  DISTRIB is a cross-tabulation matrix having one column for each
%  stimulus category and one row for each response category.
%  Alternatively, DISTRIB may be a joint-probability matrix. In this
%  case, the sum of the elements in each column should be 1.0.
%
%  XTAB2DPRIME computes signal-detection theory measures for each
%  pair of adjacent stimuli <i,i+1> as follows:
%    #FAs  -- stimulus == i  , response >= i+1
%    #CRs  -- stimulus == i  , response <= i
%    #Hits -- stimulus == i+1, response >= i+1
%    #Miss -- stimulus == i+1, response <= i
%  If the count in some cell is zero, it is set to 0.5 by default.
%  Then,  prob_Hit = #Hits/(#Hits + #Miss)
%  and    prob_FA  = #FAs /(#FAs  + #CRs )
%  Finally, these two probabilities are passed through the function DPRIME.
%
%  Reference: Luce, R., Nosofsky, R., Green, D., & Smith, A. (1982).
%    The bow and sequential effects in absolute identification.
%    Perception & Psychophysics, 32(5), 297-408. [Especially Endnote 2]
%
%  See also  DPRIME, XTAB, DPRIME_OF_PNOISE, MILLER_ANALYSIS, DATA_BY_SBJ.

% Original coding by Alex Petrov, Ohio State University
% $Revision: 1.1 $  $Date: 2000/09/28 22:00 $
%
% Part of the utils toolbox version 1.1 for MATLAB version 5 and up.
% http://alexpetrov.com/softw/utils/
% Copyright (c) Alexander Petrov 1999-2006, http://alexpetrov.com
% Please read the LICENSE and NO WARRANTY statement in ../utils_license.m

% No error checking

[N_resp,N_stim] = size(distrib) ;
N = N_stim - 1 ;

CRs  = zeros(1,N) ;     Miss = zeros(1,N) ;
FAs  = zeros(1,N) ;     Hits = zeros(1,N) ;
pFA  = zeros(1,N) ;     pHit = zeros(1,N) ;

for k = 1:N
  FAs(k)  = sum(distrib(k+1:end,k)) ;    % S == i  , R >= i+1
  CRs(k)  = sum(distrib(1:k,k)) ;        % S == i  , R <= i
  Hits(k) = sum(distrib(k+1:end,k+1)) ;  % S == i+1, R >= i+1
  Miss(k) = sum(distrib(1:k,k+1)) ;      % S == i+1, R <= i
end

if (min(sum(distrib)) > 1)     % if counts (rather than probabilities)
  FAs  = max(FAs ,0.5) ;       % guard against zero counts (they cause Inf)
  CRs  = max(CRs ,0.5) ;
  Hits = max(Hits,0.5) ;
  Miss = max(Miss,0.5) ;
end

pHit = Hits ./ (Hits + Miss) ;
pFA  = FAs  ./ (FAs + CRs) ;

[d,beta] = dprime(pHit,pFA) ;

%--Return D and BETA
%%%%% End of file XTAB2DPRIME.M
