# Finding out Q and R matrices of a given system.

2 views (last 30 days)
Misha on 22 Mar 2014
Answered: John Petersen on 28 Jul 2014
Hi everyone, I have a system with A, B, C, D matrices and I want to get a Kalman filter response, but I cannot figure out Q and R matrices. I would be really thankful if anybody could check out my code and tell me how to find Q and R matrices and get a desired response. Thank you
a=0.304;
S=a^2*pi;
v=0.015;
v3=0.03;
L=0.28;
Ts=0.01;
Sd=v*pi;
Sa=v3*pi;
g=9.81;
h10=0.06;
h20=0.04;
h30=0.02;
C13=(Sd/S)*g/sqrt(2*g*(h10-h30));
C23=(Sd/S)*g/sqrt(2*g*(h20-h30));
%state space model
A=[-C13 0 C13; 0 -C23 C23; C13 C23 -C13-C23-Sa/S*g/sqrt(2*g*h30)];
B=[1/S 0 0; 0 1/S 0; 0 0 0];
C=[1 0 0;0 1 0; 0 0 1];
D=[0 0 0; 0 0 0; 0 0 0];
Delta_t=0.01;
Q=??
R=eye(3)
Plant = ss(A,B,C,0,-1,'inputname',{'u' 'w' 'z'},...
'outputname',{'y' 'e' 'r'});
[kalmf,L,P,M]=kalman(Plant,Q,R)
kalmf = kalmf(1,:)
kalmf
a = A;
b = [1/S 0 0; 0 1/S 0; 0 0 0] ;
c = C;
d = [0 0 0;0 0 0; 0 0 0];
P = ss(a,b,c,d,-1,'inputname',{'u' 'w' 'v'},...
'outputname',{'y' 'yv' 'yz'});
sys = parallel(Plant,kalmf,1,1,[],[])
SimModel = feedback(sys,1,4,2,1)
% Delete yv from I/O list
SimModel = SimModel([1 3],[1 2 3])
SimModel.inputname
SimModel.outputname
t = [0:100]';
u = sin(t/5);
n = length(t)
randn('seed',0)
w = sqrt(Q)*randn(n,1);
z = sqrt®*randn(n,1);
[out,x] = lsim(SimModel,[w,z,u])
y = out(:,1); % true response
ye = out(:,2); % filtered response
yv = y + z; % measured response
subplot(211), plot(t,y,'--',t,ye,'-'),
xlabel('No. of samples'), ylabel('Output')
title('Kalman filter response')
subplot(212), plot(t,y-yv,'-.',t,y-ye,'-'),
xlabel('No. of samples'), ylabel('Error')

John Petersen on 28 Jul 2014
R and Q are the plant and sensor uncertainty covariance. I can't tell from your code which is which. You can start with an initial guess based on sensor specs and your understanding of the system. From there you can adjust the values as needed for your purposes.