卡尔曼(kalman)滤波学习测试例

下面两套代码一套是python,一套是matlab,效果是一样的。

PYTHON


import numpy as np
import matplotlib.pyplot as plt

t = np.arange(1, 1001)
nsig = 5 * np.sin(0.01 * t) + np.random.rand(len(t)) + np.random.randn(len(t)) + 5 * np.cos(0.05 * t + np.pi/1.5)
kf = np.zeros_like(nsig)

x = 0  # state, x(k) = a * x(k-1) + b * u(k)
a = 1  # state transfer matrix
b = 0  # control matrix
h = 1  # observer matrix
p = 0  # estimate cov
q = 0.002  # process cov
r = 0.05  # observer cov
g = 0  # kalman gain

gain = np.zeros_like(nsig)

for i in range(len(nsig)):
    x = a * x + b * nsig[i]
    p = a * p * a + q

    g = p * h / (h * p * h + r)
    x = x + g * (nsig[i] - h * x)
    p = (1 - g * h) * p

    kf[i] = x
    gain[i] = g

plt.plot(t, nsig, label="noise")
plt.plot(t, kf, label="filtered")
plt.plot(t, gain, label="kalman gain")
plt.legend()
plt.grid(which="minor")
plt.show()

MATLAB

t = 1 : 1000;
nsig = 5 * sin(0.01 * t) + rand(1, length(t)) + randn(1, length(t)) + 5 * cos(0.05 * t + pi/1.5);
kf = zeros(size(nsig));

x = 0; % state, x(k) = a * x(k-1) + b * u(k)
a = 1; % state transfer matrix
b = 0; % control matrix
h = 1; % observer matrix
p = 0; % estimate cov
q = 0.002; % process cov
r = 0.05; % observer cov
g = 0; % kalman gain

gain =zeros(size(nsig));

for i = 1 : length(nsig)
    x = a * x + b * nsig(i);
    p = a * p * a + q;

    g = p * h /(h * p * h + r);
    x = x + g * (nsig(i) - h * x);
    p = (1 - g * h) * p;

    kf(i) = x;
    gain(i) = g;
end

plot(t, nsig, t, kf, t, gain);
legend("noise", "filtered", "kalman gain");
grid minor;

在这里插入图片描述

参考文献

相关推荐

  1. 滤波

    2023-12-23 11:12:01       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-23 11:12:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-23 11:12:01       101 阅读
  3. 在Django里面运行非项目文件

    2023-12-23 11:12:01       82 阅读
  4. Python语言-面向对象

    2023-12-23 11:12:01       91 阅读

热门阅读

  1. git---分支---标签

    2023-12-23 11:12:01       51 阅读
  2. 从导航软件到游戏行业的小讨论

    2023-12-23 11:12:01       56 阅读
  3. oracle表空间对象迁移到其他表空间

    2023-12-23 11:12:01       49 阅读
  4. StringBuilder和StringBuffer区别是什么?

    2023-12-23 11:12:01       58 阅读
  5. MBA-英语二写作-小作文-范文

    2023-12-23 11:12:01       47 阅读
  6. 跨域问题的解决

    2023-12-23 11:12:01       64 阅读
  7. pytest 的 fixture 固件机制

    2023-12-23 11:12:01       55 阅读