MATLAB: How to understand the K matrix and the noisevariance of a state space model

k matrixkalman gainmeasurement noisesystem noise

My goal is to execute the Kalman filter using the raw measured temperature values. Since the system model, the measurement noise ( R ) and the system noise ( Q ) are unkown, I want to firstly use pem (prediction-error minimization method) to find a suitable state space model ( m ) for it. However, I'm confused about the estimated K matrix of pem and the noisevariance. Before I think that
R = m.noisevariance;
Q = m.K^2 * R.
But when I refer one example in matlab toolbox: Estimating a Discrete-Time Grey-Box Model with Parameterized Disturbance (the related codes are shown below), it seems that the K matrix is actually the Kalman gain. If it is, what is the noisevariance returned by pem? How can I know R and Q then?
%*************************************************************************************************************%
function [A,B,C,D,K,x0] = mynoise(par,T,aux)
R2 = aux(1); % Known measurement noise variance
A = [par(1) par(2);1 0];
B = [1;0];
C = [par(3) par(4)];
D = 0;
R1 = [par(5) 0;0 0];
[est,K] = kalman(ss(A,eye(2),C,0,T),R1,R2);
x0 = [0;0];
2. Specify initial guesses for the unknown parameter values and the auxiliary parameter value R2:
par1 = 0.1; % Initial guess for A(1,1)
par2 = -2; % Initial guess for A(1,2)
par3 = 1; % Initial guess for C(1,1)
par4 = 3; % Initial guess for C(1,2)
par5 = 0.2; % Initial guess for R1(1,1)
Pvec = [par1; par2; par3; par4; par5]
auxVal = 1; % R2=1
3. Construct an idgrey model using the mynoise file:
Minit = idgrey('mynoise',Pvec,'d',auxVal);
4.Estimate the model parameter values from data:
Model = pem(data,Minit)
%****************************************************%

Best Answer

I think I can answer this question by myself now.
The state space model in pem is considered as an innovation forms. Thus, the K matrix analzed by pem is acctually A* Kalman gain. The noise variance is the var(predicted measurement- real measurement). According to this equation, we can obtain the relationship between K, var and R,Q of Kalman filter.
Related Question