No License

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video

Highlights from
Learning the Kalman Filter

4.5 | 105 ratings Rate this file 382 Downloads (last 30 days) File Size: 7.16 KB File ID: #5377 Version: 1.0

Learning the Kalman Filter


Michael Kleder (view profile)


30 Jun 2004 (Updated )

Basic Kalman filter, heavily commented, for beginners to Kalman filtering.

Editor's Notes:

This file was selected as MATLAB Central Pick of the Week

Popular File 2008 2009 2010 2011 2012

| Watch this File

File Information

When I first studied Kalman filtering, I saw many advanced signal processing submissions here at the MATLAB Central File exchange, but I didn't see a heavily commented, basic Kalman filter present to allow someone new to Kalman filters to learn about creating them. So, a year later, I've written a very simple, heavily commented discrete filter.


This file inspired Kalman Filter Tutorial, Learning The Extended Kalman Filter, Learning The Unscented Kalman Filter, and Learning The Kalman Filter In Simulink V2.1.

MATLAB release MATLAB 5.3.1 (R11.1)
Other requirements None.
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (158)
28 Jan 2017 Angel Fernandez

IMHO this kalmanf(s) is wrong.
It should be as posted below. That gives good results.

function s = kalmanf(s)
%step 1: Compute Kalman gain factor:
K = s.P*s.H'*inv(s.H*s.P*s.H'+s.R);
%step 2: Correction based on observation:
s.x = s.x + K'*(s.z-s.H*s.x);
%step3: update error
s.P = s.P - K*s.H*s.P;

Comment only
26 Oct 2016 Meysam Tavakoli

I have started to work on application of Kalman filter to estimate parameters. My question is a little strange:
we have a simple system with 2 states (x, y) and 2 rates (K1, K2).
our equations are:

dx/dt = - K1*x + K2*y
dy/dt = K1*x - K2*y

and I am looking for the parameters (a, b, K1, K2)
also we have the actual data points for the Z(x) and Z(y)
How do I can solve this problem with Kalman filter?

16 Aug 2016 Hao Li

Hao Li (view profile)

thank you for sharing

27 May 2016 HEC

HEC (view profile)


I put a vector of observations with noises and I got an error message :

Undefined function or variable 'z'.

Error in kalmanf (line 150)
if ~isfield(s,'x'); s.x=nan*z; end

can someone help me please

Comment only
18 May 2016 Chengcheng Zhou

Thanks a lot!

11 Jan 2016 Lyudmil Vladimirov

Perparim, this is a common mistake of trying to define an M-function inside an M-script. Have a look at the explanation here:

What I am guessing you tried to do is simply un-comment the example code and run the file. Instead, copy/cut and paste the code within the brackets in a new script and try running that instead. Hope this helps!

Comment only
04 Dec 2015 Perparim Fetahi

Hello, I am getting the following error, can anyone tell me what is the issue?

Error: File: kalmanf.m Line: 147 Column: 1
Function definitions are not permitted in this context.

Comment only
17 Nov 2015 Evan Lucas

30 Sep 2015 Nguyen Manh Tuong

Please! Give me a example of kalmanf function.

Comment only
23 Apr 2015 sami omar

hey guys,
Im new to matlab, Im trying to implement Kalman filter with sin wave is that possible?

Comment only
17 Apr 2015 Auralius Manurung

Line 173, file kalmanf.m

s.P = s.A * s.P * s.A' + s.Q;

this is wrong, it should be:

s.P = s.A * s.P * s.A' + s.B * s.Q * s.B';

the example is also misleading, see cooment by Yi Cao (25 Jan 2008) since be should not be = 0 but B should be = 1.

Comment only
19 Jan 2015 Xiang CAo

29 Nov 2014 Yiman

Yiman (view profile)

thank you,I like it

Comment only
17 Nov 2014 kushwinder singh

its very helpful

06 Aug 2014 venugopal kulkarni

06 May 2014 Carlos M. Velez S.

A good complement of linear Kalman filter in Simulink:

Comment only
24 Apr 2014 Koranit

24 Apr 2014 Koranit

31 Jan 2014 Angel Lopez

very useful!! Thanks a lot.

23 Dec 2013 anthony

how do i view the document

Comment only
21 Nov 2013 Aaron Schurger

Aaron Schurger (view profile)

Excellent resource for those of us who are new to Kalman filtering. Thank you! What if the state of my system is given by a vector rather than a scalar? Can Kalman filtering work in n dimensions? If I want to train the filter on one set of data and then apply it to another, how would I do that? What if my observations are a sum of two or more signals, plus noise? How do I "tell" the Kalman filter which of the signals I want it to estimate?

26 Aug 2013 liliaceae

nice documentation and easy to understand.

26 Aug 2013 liliaceae

17 Jul 2013 Aliakbar Alamdari

Very nice implementation. But there is a minor mistake in the Kalman filter block. In propagation equation, 1/Z must be placed in somewhere else. We have P(k+1) = A.P(k).A' + Q. after this part we have to put 1/z to get P(k).

10 Apr 2013 jakub

jakub (view profile)

In other words, how to draw their values​​, provided they are stored in my data.mat?
Will the "plot" are the same and I have to use a loop "for"?
Ask directly about the code sample, it's here I deal with a couple of hours.

Comment only
09 Apr 2013 jakub

jakub (view profile)

My case:

>> clear s
>> s.x = 12;
>> s.A = 1;
>> s.Q = 2^2;
>> s.H = 1;
>> s.R = 2^2;
>> s.B = 0;
>> s.u = 0;
>> s.x = nan;
>> s.P = nan;

>> s.z = [1 2 3 4 5 6 7 8 9 22 3 4 5 6 7 8 88];
>> kalmanf(s);

>> figure
>> hold on
>> grid on
>> hz=plot(s.z,'r.')
>> hk=plot(s,'b-')

Error using plot
Conversion to double from struct is not possible.

Where is the problem ?

Thank u

Comment only
13 Feb 2013 zhang blue

07 Feb 2013 Tim

Tim (view profile)

07 Feb 2013 Tim

Tim (view profile)

I am new to k. filtering, and I don't understand the following: the covariance matrix P appears to be only a function of the following inputs: A (defined by the system), P (itself), Q (known p.noise cov.), and H (typically identity), and also the Kalman gain K. K itself is a function only of P, H, and R (known m.noise cov.).

None of these are re-defined during iteration except P. How then is the estimate of the covariance matrix P tied to observations z? The result of this appears to be that the Kalman gain explodes by the third or fourth iteration, making the output mirror the noisy input. This seems to be what Enver Bahar is noticing too, I think.

22 Jan 2013 NAGA VBN

Actually iam getting the error s not defined what can i do for this and this example gives v.gud idea.

09 Jul 2012 Markus Schmidt

thank you Shamir Alavi.

Comment only
09 Jul 2012 Shamir Alavi

[rectification to the post above]: sry, 's' is not the measurement data. your data goes into 's.z' here.

Comment only
09 Jul 2012 Markus Schmidt

got an error with

>> s = [1 2 3 4 5 6 7 8 9 22 3 4 5 6 7 8 88];

>> kalmanf(s);
Undefined function or variable 'z'.

Error in kalmanf (line 150)
if ~isfield(s,'x'); s.x=nan*z; end

Can someone explain me why pls?

Comment only
22 Jun 2012 weijie

weijie (view profile)

you are awesome

18 Jun 2012 vamshi

vamshi (view profile)

13 Mar 2012 Carolina Brum Medeiros

helpful and clear comments

25 Feb 2012 Roja e

Roja e (view profile)

Thanks..but an error occurred while running this demo.
Input argument "s" is undefined
help me please

18 Feb 2012 chao

chao (view profile)

11 Feb 2012 Ruban Sugumar

Nice Explanation..
Really Helpful..

05 Aug 2011 greg

greg (view profile)

Nicely documented.
As a practicing engineer I would never use the implementation shown. This is the standard covariance form of the Kalman filter. In operation the statement
s.P = s.P - K*s.H*s.P;
causes significant issues. s.P needs to always be positive definite but with rounding this will tend to violate this assmption making the Kalman filter 'blow up' over time or with poorly conditioned data.

The alternative is to process in the square root domain where the P matrix is expressed as a P=Psr'*Psr. Therefore the resuting matrix must always be positive definite and does not have this issue. An added advantage is the precision is doubled processing in this domain and can be similar to the input data resolution rather than 2x the number of bits to provide comparable precision.

For more information see
'Linear estimation' Kailath, Sayed, Hassibi or
'adaptive filter thoery' Haykin

IMHO one should always to filtering in the SR domain. There are also advantages of processing with separated real/imag data rather then complex if the underling data is complex.

Comment only
22 Jul 2011 prokash paul

nice doc

16 Jul 2011 lotfi

lotfi (view profile)

good !

Comment only
27 Jun 2011 Edgar lobachevskiy

excellent!! Thank you!!

02 Jun 2011 Liu Kefeng

thank you very much!


10 Apr 2011 Ms. Mat

What is the difference between this and kalman implementation in Control System toolbox ?

Comment only
01 Apr 2011 Raven

Raven (view profile)

29 Mar 2011 Karthik MSwamy


15 Jan 2011 Henry Zhu

Dear Michael Kleder,thank you !

24 Nov 2010 osman Özkaraca


Comment only
22 Nov 2010 zheng

zheng (view profile)

love you so much, your sample is more helpful than those books wrote by some professional guys. easy, straightforward. especially for beginners.

Comment only
12 Nov 2010 Joan

Joan (view profile)

25 Oct 2010 Enver

Enver (view profile)

Thanks a lot because of your great explanation.

But, I have a simple question, why results don't change when we give very high measurement noise?
You gave standart deviation as 2 in your example, but when I make it for example 1000, it estimates perfectly. Doesn't supposed to change?

Can anyone explain this to me?
Thanks a lot

24 Sep 2010 Daniel Armyr

Daniel Armyr (view profile)

Good commenting, byt unfortunately, the code is wrong in several places. It absolutely does not handle vector inputs and some inputs that are defined as optional will cause the program to crash if they are not provided. From a file that is top ranked on the file exchange, I expected alot more.

23 Sep 2010 Richard

Richard (view profile)

awesome! makes so much more sense now. thanks.

Comment only
19 Aug 2010 Steve G

Very clean example of KF, but not general enough to deal with state vectoc. For example, s.x = inv(s.H)*s.z; and s.P = inv(s.H)*s.R*inv(s.H') would not work if number of state and number of measurement are not the same.

Comment only
17 Aug 2010 Baboon LikesBananas

11 Aug 2010 Big Andy

21 Jul 2010 joybing

thank you for sharing!

Comment only
12 Jul 2010 Erdal Bizkevelci

10 Jun 2010 Venche

Venche (view profile)

sehr gut!

09 Jun 2010 John D

John D (view profile)

[continued from poste above]

As expected my matrices were wrong!

Thanks for the example!

Comment only
09 Jun 2010 John D

John D (view profile)

[continued from poste above]

I have solved the problem by modifying the line to;

>> s.x = s.x + K' * (s.z-s.H*s.x); %added transpose of K

This was required as my observance vector (z) was a 2X1 matrix(and so is K and hence they couldn't be multiplied). Although the calculation now works I am still wondering why it doesnt work with the original code.

Comment only
08 Jun 2010 John D

John D (view profile)

I get an error during the correction step.
>> s.x = s.x + K*(s.z-s.H*s.x);

Error using==>mtimes
Inner matrix dimensions must agree

The error makes sense given the size of my matrices but I don't see how they could be wrong. Is this code expected to not work for a system with two observer inputs (position and speed)?

Thanks for the help!
ps: let me know if you need more info - tried to keep it short.

06 Jun 2010 ?

? (view profile)

Thanks very much.

06 Jun 2010 Steven

Steven (view profile)

21 May 2010 Examples Learn By

Thank you for your hard work

Comment only
01 Apr 2010 chen

chen (view profile)

thank your

Comment only
29 Mar 2010 vu

vu (view profile)


Comment only
18 Mar 2010 Toto

Toto (view profile)

Great job !

Comment only
03 Mar 2010 Gervasio

Very Helpful, although i would like to see an example with a control vector u.



is there anyone got the right solution in learning Kalman Filter.
Could you email file.m to me,
I've run the file given but have alot error.
Please help me.

24 Jul 2009 naini naveen

very good

Comment only
24 Jun 2009 Shivaram

Excellent KF implementation I have ever seen!

06 Apr 2009 benouis mohamed


26 Jan 2009 Michael Jordan

11 Nov 2008 Prasetyo Utomo

Thanks very much

Comment only
26 Sep 2008 mohammad khorrami arani


Comment only
21 Jul 2008 Tim Davis

Nice comments. Awful numerics. Why would you consider multiplying by the inverse? That's horribly inaccurate and slow. Replace

x = inv(H)*z
P = inv(H)*R*inv(H')

with, at least

x = H\z
P = (H\R)/H'


K = P * H' * inv (lots of stuff)

should be

K = P * H' / (lots of stuff)

further more, if H is not changing, it should be factorized just once and the factors kept (LU or CHOL).

13 Jul 2008 Vipin Gupta

Thanks for sharing. :)

03 Jul 2008 Imtiaz Hussain

Very Useful Indeed

19 Jun 2008 Sid Saraiya

This was extremely useful for a beginner like me. A great post!

03 Jun 2008 Behnam Molaee Ardekani

Good for those who want to see what the Kalman Filter is for the first time.
It works and there is a simple example in the m file.

27 Apr 2008 Sahil Ganguly

I keep getting this error,can someone explain what i'm doing wrong?

kalmanf ??? Input argument "s" is undefined. Error in ==> kalmanf at 150 if ~isfield(s,'x'); s.x=nan*z; end

22 Apr 2008 bekir pasaoglu


03 Mar 2008 mohamed pumma


Comment only
25 Jan 2008 Yi Cao

This is a very popular file in the File Exchange. The function itself is excelent. However, I just noticed that the example provide with the file is not correct. Somehow, it is misleading to beginers.

In line 131, the process is defined as:
true(end+1) = randn*2 + 12;
i.e. the state is a constant plus a noise. If so, the process in the standard state space form should be:
x(k+1) = 0 * x(k) + 12 + w(k)
i.e. s.A = 0; s.B = 1; s.u = 12;
However, in the file it is wrongly defined as:
s.A = 1; s.B = 0; s.u = 0;
The difference is that the process noise is not dynamically cumulated in the former definition but does in the later.

04 Jan 2008 marc luc

31 Dec 2007 James Hokanson

27 Dec 2007 Arsalan Khan

I can understand Kalman filter from this document, I bet anyone can.

Comment only
28 Nov 2007 Randy Coleman

27 Nov 2007 wang yi

very good

Comment only
06 Nov 2007 P. McNamara

Be careful. Also we are looking at your downloads records.

Comment only
19 Oct 2007 djeunang brigitte

i want a kalman filter

Comment only
05 Oct 2007 Utkarsh Gaur

04 Oct 2007 Duong Minh Au

11 Jul 2007 hamid reza ghazizadeh

how con I find calculation of dry gas filter
for natural gas ? please

Comment only
14 Jun 2007 X. King

10 Jun 2007 sk imtiaj

this is very good

Comment only
07 Jun 2007 Bouchemmella abdelhalim

I want this refference

29 May 2007 mehmet ali arabaci

Actually, I am not a beginner at Kalman filter issue. But, i think this is a very useful tool and i wish i got this m-file when i first started to work with Kalman. Because, it is very important for the beginners to have the simplest form of the problem and to see its solution with a simulation program.

23 May 2007 SOURAV DAS

It is a very user friendly, recommended

Comment only
15 May 2007 Edward Taylor

Very easy to use, recommended.

09 May 2007 zhu Yi Yong zhuyiyong

very good

Comment only
29 Apr 2007 Rodrigo Badínez

Good demo.
You probably should separete the example, to another m file, named like RunMeDemoKalman.
For the really beginners.

26 Apr 2007 lai zuomei

a good demo for me!

Comment only
25 Apr 2007 xu zheng

very good tools
thank you very much

29 Mar 2007 Rajesh Krishnan

28 Mar 2007 fatemeh shoormij

discrete kalman filter

Comment only
13 Mar 2007 v ram

13 Mar 2007 Way Jch

08 Jan 2007 u v

11 Dec 2006 karim kiko

It will be better if you separate the comment from the m.file and try to add them as "help" in a pdf format.

Comment only
30 Nov 2006 ravindar reddy

14 Nov 2006 Tansel Yucelen

Same Error !!!


29 Oct 2006 Priyanka Gupta

I get the same error:

??? Input argument "s" is undefined.

Error in ==> kalmanf at 150
if ~isfield(s,'x'); s.x=nan*z; end

Comment only
26 Oct 2006 clayonjj Harrison

i like the explanation but I cant run the file the following error pops up.HELP!!

??? Input argument "s" is undefined.

Error in ==> kalmanf at 150
if ~isfield(s,'x'); s.x=nan*z; end

Comment only
17 Oct 2006 shao litang

I need Kalman Filter program.

Comment only
27 Aug 2006 diop bara


Comment only
15 Aug 2006 Colin O'Flynn

Thank You! Great introduction to the Kalman filter, even if you don't use Matlab.

14 Jun 2006 ti toe

you have to set up matlab first and run with workspace

26 Apr 2006 Bing Li

try to replace inv(A)*B by A\B to speed up, although it's not significant when the matrix size is small

Comment only
23 Apr 2006 Teo chai

I try to run the "learning the kalman filter" in the matlab but i unable to run it.
May i know how to run the file? thks

13 Apr 2006 Indiana Jones

06 Apr 2006 Carlos Orduno

The best source I've found to start working with Kalman Filters. Do you have anything for the nonlinear version?

29 Mar 2006 Camilo Lozoya

22 Feb 2006 swami nathan

15 Feb 2006 Franz Dietrich

Useful Comments in Code.

09 Feb 2006 Eduardo Veras

20 Jan 2006 akher falcon

its great.

Comment only
13 Jan 2006 Xuewu Dai

Very Useful for understanding Kalman Filter

12 Jan 2006 Carlos Roldan

07 Jan 2006 Robert Kaddu

Very well presented summary that makes more sense than that provide within the Matlab help function.



25 Dec 2005 Mehdi Sanaatiyan

Well,it's good for first time.No at all

20 Nov 2005 Rafal G.

Simple, pretty, excellent :-))) Thanks a lot!!

15 Nov 2005 nemesio CARDENAS LOPES


29 Oct 2005 Zahid Ullah Khan

Its nice, no doubt.

21 Oct 2005 shobi kumar

excellent apporach
but i m unable to run this prog
plz help me

03 Aug 2005 Tsanko Tsankov

A good try to explain something. Keep up the good work! There are, however, some mistakes (at the autoinitialization step). Anyway I still don't quite understand the use of Kalman filter. The given example is good, but I'm still confused how to apply this filter to my data.

10 Jul 2005 ammar saleem

08 Jul 2005 Rentian Xiong

Nice work. It would be better if there is an example for vector state. Also it would be very cool if someone can put Kalman filter algorithm in simulink so that we can see the estimation of states dynamically. And of course, an extended kalman filter for nonlinear system would be also very useful.

30 Jun 2005 lee yk

Would you like to give me sample 's' value?
I still don't understand it perfectly.

29 Jun 2005 Tim Gebbie

Very fun. Very neat.

16 Jun 2005 Flop Flop


very good, I like the idea

30 Mar 2005 Daniel O. Fufa

very good
Thanks Daniel
Aalborg university

Comment only
23 Mar 2005 Nathir Rawashdeh

This is a very good example and shows how easy it is to apply the Kalman filter. It does, however, require some background knowledge. It would be nice to have a more complicated example with non-zero u and where H and A are not =1. Thanks Michael!

23 Mar 2005 Liu Baolong

You are a great tutor !
I really appreciate it .
Thank you very much.


21 Jan 2005 Giuliano Scimone

14 Jan 2005 Simon Tippler

Very helpful. Thanks!!

11 Jan 2005 Hooman Dejnabadi

29 Nov 2004 Thomas Byrne

Excellent!! Thank You.

Comment only
05 Oct 2004 Vassilios Moussas

Compact, well documented, very good initialization and use of structures.

23 Sep 2004 Giap Do van


Comment only

Contact us