% Problem Set3 - Problem 7
%
% *Recursive Least Squares*
%
% Recursive Filtering and Estimation
% Spring 2010
%
% --
% ETH Zurich
% Institute for Dynamic Systems and Control
% Angela Schöllig
% aschoellig@ethz.ch
%
% --
% Revision history
% [01.04.10, AS]    first version
%


clear

% Use 0 for normally distributed, CRV, 1 for DRV equally likely at +-1
DISTRIBUTION_TYPE = 0;

% Set the state of the normally distributed random number generator.
randn('state',0);

% Number of time samples. 100, 1000, or 10000
N = 1e4;
xEstLin = zeros(N+1,1);
xEstNL = zeros(N+1,1);

% Generate the true value of x
if DISTRIBUTION_TYPE == 0
   xActual = randn;
else
   xActual = sign(randn);
end

% Simulation
xEstLin(1) = 0;
xEstNL(1) = 0;
for k = 1:N
    
    if DISTRIBUTION_TYPE == 0
        w = randn;
    else
        w = sign(randn);
    end
    
    % Generate simulated measurement
    z = xActual + w;
    
    % The optimal linear estimator
    K = 1/(1+k);
    xEstLin(k+1) = xEstLin(k) + K*(z - xEstLin(k));
    
    % The nonlinear estimator, which only makes sense for discrete random
    % variables. Case 1: we have already determined what x is
    if (abs(xEstNL(k)) > 0.5)
        xEstNL(k+1) = xEstNL(k);
    else
        % Otherwise, we have to look at the measurement.  If z = 0, then it
        % is equally likely that x = 1 or -1.  If z = 2, then x must be 1.
        % If z = -2, then x must be -1
        if (abs(z) < 1)
            xEstNL(k+1) = 0;
        elseif (z > 1)
            xEstNL(k+1) = 1;
        else
            xEstNL(k+1) = -1;
        end
    end
end

% Plot the results
figure(1)
plot(0:N,xEstLin,'*',0:N,xEstNL,'o',0:N,xActual,'r.');
legend('Linear Estimate','Non-linear Estimate','Actual');

findfigs
