function price = ExampleLS;
% this function replicates example 1 on pages 115-120 of the 
% original paper by Longstaff and Schwartz
X = 1.1;
r = 0.06;
T = 3;
NSteps = 3;
NRepl = 8;
dt = T/NSteps;
discount = exp(-r*dt);
discountVet = exp(-r*dt*(1:NSteps)');
a = zeros(3,1); % regression parameters
% generate sample paths
SPaths = [
    1.09 1.08 1.34
    1.16 1.26 1.54
    1.22 1.07 1.03
    0.93 0.97 0.92
    1.11 1.56 1.52
    0.76 0.77 0.90
    0.92 0.84 1.01
    0.88 1.22 1.34
];
%
CashFlows = max(0, X - SPaths(:,NSteps));
ExerciseTime = NSteps*ones(NRepl,1);
for step = NSteps-1:-1:1
    InMoney = find(SPaths(:,step) < X);
    XData = SPaths(InMoney,step);
    RegrMat = [ones(length(XData),1), XData, XData.^2];
    YData = CashFlows(InMoney) .* discountVet(ExerciseTime(InMoney) - step);
    a = RegrMat \ YData;
    IntrinsicValue = X - XData;
    ContinuationValue = RegrMat * a;
    Exercise = find(IntrinsicValue > ContinuationValue);
    k = InMoney(Exercise);
    CashFlows(k) = IntrinsicValue(Exercise);
    ExerciseTime(k) = step;
end % for
price = mean(CashFlows.*discountVet(ExerciseTime));