Matlab:实现卡尔曼滤波器时逆运算出错

Matlab: Error in inverse operation when implementing Kalman filter

我正在尝试为以下一维 AR 模型实现卡尔曼滤波器的基本方程:

x(t) = a_1x(t-1) + a_2x(t-2) + w(t)  

y(t) = Cx(t) + v(t);

KF状态space型号:

x(t+1) = Ax(t) + w(t)

y(t) = Cx(t) + v(t)

w(t) = N(0,Q)

v(t) = N(0,R)

哪里

 % A - state transition matrix
% C - observation (output) matrix
% Q - state noise covariance
% R - observation noise covariance
% x0 - initial state mean
% P0 - initial state covariance


%%% Matlab script to simulate data and process usiung Kalman for the state
%%% estimation of AR(2) time series.
% Linear system representation
% x_n+1 = A x_n + Bw_n
% y_n = Cx_n + v_n
% w = N(0,Q); v = N(0,R)
clc
clear all

T = 100; % number of data samples
order = 2;
% True coefficients of AR model
  a1 = 0.195;
  a2 = -0.95;

A = [ a1  a2;
      0 1 ];
C = [ 1 0 ];
B = [1;
      0];

 x =[ rand(order,1) zeros(order,T-1)];



sigma_2_w =1;  % variance of the excitation signal for driving the AR model(process noise)
sigma_2_v = 0.01; % variance of measure noise


Q=eye(order);
P=Q;




%Simulate AR model time series, x;



sqrtW=sqrtm(sigma_2_w);
%simulation of the system
for t = 1:T-1
    x(:,t+1) = A*x(:,t) + B*sqrtW*randn(1,1);
end

%noisy observation

y = C*x + sqrt(sigma_2_v)*randn(1,T);

R=sigma_2_v*diag(diag(x));
R = diag(R);

z = zeros(1,length(y));
z = y;

 x0=mean(y);
for i=1:T-1
[xpred, Ppred] = predict(x0,P, A, Q);
[nu, S] = innovation(xpred, Ppred, z(i), C, R);
[xnew, P] = innovation_update(xpred, Ppred, nu, S, C);
end

%plot
xhat = xnew';


plot(xhat(:,1),'red');
hold on;
plot(x(:,1));



function [xpred, Ppred] = predict(x0,P, A, Q)
xpred = A*x0;
Ppred = A*P*A' + Q;
end

function [nu, S] = innovation(xpred, Ppred, y, C, R)
nu = y - C*xpred; %% innovation
S = R + C*Ppred*C'; %% innovation covariance
end

function [xnew, Pnew] = innovation_update(xpred, Ppred, nu, S, C)
K = Ppred*C'*inv(S); %% Kalman gain
xnew = xpred + K*nu; %% new state
Pnew = Ppred - Ppred*K*C; %% new covariance
end

代码抛出错误

Error using inv
Matrix must be square.

Error in innovation_update (line 2)
K = Ppred*C'*inv(S); %% Kalman gain

Error in Kalman_run (line 65)
[xnew, P] = innovation_update(xpred, Ppred, nu, S, C);

这是因为S矩阵不是方阵。我怎样才能让它变成正方形?是不是之前的步骤有问题?

据我了解,R矩阵应该是测量噪声的协方差矩阵。

以下几行:

R=sigma_2_v*diag(diag(x));
R = diag(R); 

R 从 2x2 对角矩阵更改为 2x1 列向量。

由于您的观察 y 是标量,因此观察噪声 v 也必须是标量。这意味着 R 是一个 1x1 协方差矩阵,或者只是随机变量 v.

的方差

您应该使 R 成为您的代码正常工作的标量。