卡尔曼滤波C语言代码v2.0
#include <stdio.h>
#include <math.h>
#define dt 1.0
#define Q 0.01
#define R 0.1
typedef struct {
double position;
double velocity;
} State;
typedef struct {
double P00, P01;
double P10, P11;
} Covariance;
void Kalman_Init(State *state, Covariance *P) {
state->position = 0.0;
state->velocity = 0.0;
P->P00 = 1.0;
P->P01 = 0.0;
P->P10 = 0.0;
P->P11 = 1.0;
}
void Kalman_Predict(State *state, Covariance *P) {
double temp_position = state->position;
double temp_velocity = state->velocity;
state->position = temp_position + dt * temp_velocity;
state->velocity = temp_velocity;
double temp_P00 = P->P00;
double temp_P01 = P->P01;
double temp_P10 = P->P10;
double temp_P11 = P->P11;
P->P00 = temp_P00 + dt * temp_P01 + dt * temp_P10 + dt * dt * temp_P11 + Q;
P->P01 = temp_P01 + dt * temp_P11;
P->P10 = temp_P10;
P->P11 = temp_P11 + Q;
}
void Kalman_Update(State *state, Covariance *P, double measurement) {
double H00 = 1.0;
double H01 = 0.0;
double S = H00 * P->P00 + H01 * P->P10;
double K0 = (H00 * P->P00 + H01 * P->P10) / S;
double K1 = (H00 * P->P01 + H01 * P->P11) / S;
static double y = 0.0;
if(measurement < 1.0)
{
}else{
y = measurement - state->position;
}
state->position += K0 * y;
state->velocity += K1 * y;
P->P00 -= K0 * H00 * P->P00 + K0 * H01 * P->P10;
P->P01 -= K0 * H00 * P->P01 + K0 * H01 * P->P11;
P->P10 -= K1 * H00 * P->P00 + K1 * H01 * P->P10;
P->P11 -= K1 * H00 * P->P01 + K1 * H01 * P->P11;
}
int main() {
State state;
Covariance P;
Kalman_Init(&state, &P);
double measurements[] = {1.2, 2.1, 3.0, 4.1, 5.0, 3.1, 7.0, 8.1, 9.0, 10.1, 0,0,0,0,0};
int num_measurements = sizeof(measurements) / sizeof(measurements[0]);
for (int k = 0; k < num_measurements; k++) {
Kalman_Predict(&state, &P);
Kalman_Update(&state, &P, measurements[k]);
printf("Time: %d, Position: %.2f, Velocity: %.2f\n", k, state.position, state.velocity);
}
return 0;
}
