%% Use a Single System object to Track Multiple Scalar Values
% *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 signal where the columns are the two scalar values to be tracked. 
% Also create the Kalman Filter, and the Time Scopes.
% Copyright 2020 The MathWorks, Inc.
numSamples = 4000;
R = 0.02;
src = dsp.SignalSource; 
sig1 = [  ones(numSamples/4,1);   -3*ones(numSamples/4,1);...
         4*ones(numSamples/4,1); -0.5*ones(numSamples/4,1)];
sig2 = [-2*ones(numSamples/4,1);   4*ones(numSamples/4,1);...
        -3*ones(numSamples/4,1); 1.5*ones(numSamples/4,1)];  

src.Signal = [sig1, sig2];

tScope1 = timescope('NumInputPorts', 3,...
           'TimeSpanSource','Property','TimeSpan', numSamples, ...
           'TimeUnits', 'Seconds', 'YLimits',[-5 5], ...
           'Title', ['True(channel 1), noisy(channel 2) and ',...
           'estimated(channel 3) values'], ...
           'ShowLegend', true); 
tScope2 = clone(tScope1);
kalman = dsp.KalmanFilter('ProcessNoiseCovariance', 0.0001,...
    'MeasurementNoiseCovariance', R,...
    'InitialStateEstimate', -3,...
    'InitialErrorCovarianceEstimate', 1,...
    'ControlInputPort',false);
%% 
% Add noise to the signal. Stream the data, and plot the filtered signal.
%%
while(~isDone(src))
    trueVal = src();
    noisyVal = trueVal + sqrt(R)*randn(1,2);
    estVal = kalman(noisyVal);
           % Plot results of first channel on Time Scope
    tScope1(trueVal(:,1),noisyVal(:,1),estVal(:,1));  
           % Plot results of second channel on Time Scope
    tScope2(trueVal(:,2),noisyVal(:,2),estVal(:,2));  
end