%% Design Kalman Filter for SISO Plant
% Design a Kalman filter for a plant that has additive white noise w on the input and v on the output, as shown in the following diagram.
%
% Assume that the plant has the following state-space matrices and is a discrete-time plant with an unspecified sample time (Ts = -1).

A = [1.1269   -0.4940    0.1129 
     1.0000         0         0 
          0    1.0000         0];

B = [-0.3832
      0.5919
      0.5191];

C = [1 0 0];

D = 0;

Plant = ss(A,B,C,D,-1);
Plant.InputName = 'un';
Plant.OutputName = 'yt';

%
% To use kalman, you must provide a model sys that has an input for the noise w. Thus, sys is not the same as Plant, because Plant takes the input un = u + w. You can construct sys by creating a summing junction for the noise input.

Sum = sumblk('un = u + w');
sys = connect(Plant,Sum,{'u','w'},'yt');

% Equivalently, you can use sys = Plant*[1 1].
%
% Specify the noise covariances. Because the plant has one noise input and one output, these values are scalar. In practice, these values are properties of the noise sources in your system, which you determine by measurement or other knowledge of your system. For this example, assume both noise sources have unit covariance and are not correlated (N = 0).

Q = 1;
R = 1;
N = 0;

%
% Design the filter.

[kalmf,L,P] = kalman(sys,Q,R,N);
size(kalmf)

%
% The Kalman filter kalmf is a state-space model having two inputs and four outputs. kalmf takes as inputs the plant input signal u and the noisy plant output y=y_t+v. The first output is the estimated true plant output \hat{y}. The remaining three outputs are the state estimates \hat{x}.  Examine the input and output names of kalmf to see how kalman labels them accordingly.

kalmf.InputName
kalmf.OutputName

%
% Examine the Kalman gains L. For a SISO plant with three states, L is a three-element column vector.

L

% For an example that shows how to use kalmf to reduce measurement error due to noise, see Kalman Filtering.
%
% Copyright 2020 The MathWorks, Inc.