function L = AD(p, R, N)
% Octave/MATLAB function to compute Arrow-Debreu
% prices by Jamshidian's forward induction.
% INPUTS:                             (Example)
%   p =  NxN matrix of up probs.      (all 0.5)
%   R =  NxN matrix of riskless Rs  (all 1.002)
%   N =  binomial tree height, must be >1   (9)
% OUTPUTS:
%   L = Arrow-Debreu prices lambda(n,j).
% EXAMPLE:
%   L = AD(0.5*ones(9,9), 1.002*ones(9,9), 9)
%
  L=zeros(N+1,N+1); % allocate the output matrix
  L(1,1)=1;  % special case: lambda(n=0,j=0)=1
  L(2,1)=(1-p(1,1))/R(1,1); % (1,0) is special
  L(2,2)=p(1,1)/R(1,1);     % (1,1) is special
  for n=2:N  % rows n>1 need inner j loops:
    L(n+1,1)=(1-p(n,1))*L(n,1)/R(n,1); % (n,0)
    L(n+1,n+1)=p(n,n)*L(n,n)/R(n,n);   % (n,n)
    for j=1:n-1  % (n,j), 0<j<n
      L(n+1,j+1)=( p(n,j)*L(n,j)/R(n,j)
        + (1-p(n,j+1))*L(n,j+1)/R(n,j+1) );
    end
  end
  return; % L(n+1,j+1) now holds lambda(n,j)
end
