%Exercise (2b), ex sheet 1

N = 1000;
M = 1000;
Delta_t = 1/N;
%times = zeros(1,M);
n_term = N*[1 2 3 4 5 6 7 8 9 10];
average_time = zeros(1,10);
%xi2 = 2*(unidrnd(2,M,N)-1) - 1; %iid uniform rv's with P(xi2=1) = P(xi2=-1) = 1/2

for k=1:10
    times = zeros(1,M);
    for m=1:M
        x = 0; %reset x
        n = 0; %reset clock
        while (x < 0.5) && (n<n_term(k)) %need to terminate the process, otherwise numerically instable
            x = x + sqrt(Delta_t)*randn(1);
            n = n+1; %clock
        end;
        times(m) = Delta_t*n;
    end;
    average_time(k) = mean(times);
end;

%Plot performance of terminated estimator
figure;
plot(n_term*Delta_t, average_time,'--rs');
xlabel('termination time')
ylabel('estimated first arrival time')
title('performance of estimator')

%Plot a trajectory