%% Estimate Changing Scalar
% *Note*: If you are using R2016a or an earlier release, replace each call 
% to the object with the equivalent step syntax. For example, obj(x) 
% becomes  step(obj,x).
% 
% Create the System objects for the changing scalar input, the Kalman filter, 
% and the scope (for plotting).

numSamples = 4000;
R = 0.02;
src = dsp.SignalSource;
src.Signal = [ones(numSamples/4,1);-3*ones(numSamples/4,1);...
    4*ones(numSamples/4,1); -0.5*ones(numSamples/4,1)];
tScope = dsp.TimeScope('NumInputPorts',3,'TimeSpan',numSamples, ...
    'TimeUnits','Seconds','YLimits',[-5 5], ...
    'ShowLegend',true); % Create the Time Scope
kalman = dsp.KalmanFilter('ProcessNoiseCovariance', 0.0001,...
    'MeasurementNoiseCovariance',R,...
    'InitialStateEstimate',5,...
    'InitialErrorCovarianceEstimate',1,...
    'ControlInputPort',false); %Create Kalman filter
%% 
% Add noise to the scalar, and pass the result to the Kalman filter. Stream 
% the data, and plot the filtered signal.
%%
while(~isDone(src))
   trueVal = src();
   noisyVal = trueVal + sqrt(R)*randn;
   estVal = kalman(noisyVal);
   tScope(noisyVal,trueVal,estVal);
end