version 1.0.0.0 (2.1 KB) by
Yi Cao

An implementation of Extended Kalman Filter for nonlinear state estimation.

**Editor's Note:** This file was selected as MATLAB Central Pick of the Week

This is a tutorial on nonlinear extended Kalman filter (EKF). It uses the standard EKF fomulation to achieve nonlinear state estimation. Inside, it uses the complex step Jacobian to linearize the nonlinear dynamic system. The linearized matrices are then used in the Kalman filter calculation.

The complex step differentiation seems improving the EKF performance particularly in accuracy such that the optimization and NN training through the EKF are better than through the UKF (unscented Kalman filter, http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=18217&objectType=FILE). Other complex step differentiation tools include the CSD Hessian available at http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=18177&objectType=FILE.

Yi Cao (2021). Learning the Extended Kalman Filter (https://www.mathworks.com/matlabcentral/fileexchange/18189-learning-the-extended-kalman-filter), MATLAB Central File Exchange. Retrieved .

Created with
R2007a

Compatible with any release

**Inspired by:**
Learning the Kalman Filter

**Inspired:**
Learning the Unscented Kalman Filter, Unconstrained Optimization using the Extended Kalman Filter, Neural Network training using the Extended Kalman Filter

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!Create scripts with code, output, and formatted text in a single executable document.

Jay shankar NandaI am facing a problem while running this code

error is like Maximum recursion limit of 500 reached. Use set(0,'RecursionLimit',N) to change the limit. Be aware that exceeding your

available stack space can crash MATLAB and/or your computer.

Error in ekf>create@(x)[x(2);x(3);0.05*x(1)*(x(2)+x(3))]

Can anyone help how to fix this

Veronica EcheverriaDear Yi Cao. Thank you very much for this great explanation. I have a question regarding the measurement mapping matrix.

My system is -k grad(T) =q , I want to study the heat conductivity as a function of the temperature change. Therefore, I discretize my system with Finite Differences and obtain let's say 10 temperature nodes+the variable "k", which I want to predict as well. If I measure all of my discretized nodes, but I don't measure k, because it's physically infeasible, how can I do the mapping function h()?

yw liuweiMushahid Hussainhi sir im having trouble in understanding JASSCAD function can you explain it?

Nauman Ali LarikwenlongZihao ZhouGreat code, thank you.

However, I just modified the state equations with the inclusion of function F(t,x) whereby F is the Hodgkin-Huxley model function

i.e.

f=@(x) x + F(k,x)+ B*I; % nonlinear state equations

h=@(x) C * x; % measurement equation

s=[-54.3 rand rand rand]';

then I always have the following error notice:

Error using chol

Matrix must be positive definite.

Error in ekf (line 60)

R=chol(H*P12+R); %Cholesky factorization

May I know how should I resolve this situation and plot the result?

Miguel Budag BeckerHey Nathan Ellis,

I looked into your problem and found that both equations are right, because P is symmetric. So P = P', and then P12'=HP'=HP.

Frank Owusuwant to implement the EKF on a time series data... but I'm really struggling with errors for just trying to run this function.. anyone to guide me on this? It's very urgent

Muhammad ZahidMuhammad ZahidHow to use EKF for Freeway Traffic Density Estimation ? Please somebody Guide mee

Abdulrahman AlabrashKathy MansonWhy didn't you use the EKF simulink function block?

Fajar PratamaWhere is the Taylor progression ? Is there no need taylor progression in this ekf function ? because in other paper that i read there is require the taylor regression. pls help me out . Thankyou

yu junKaju BubanjaFabrizio SchianoIs there a tutorial about this? Where can I find it? Thanks

Zhiwen ChenOmar AljanaidehFor those who got Error in ==> elf at 51

Just make sure that the MATLAB directory is same as the file location.

Nathan EllisI think there might be a mistake in the commented out alternative covariance update equation:

% P = P-K*P12';

P12 was previously defined as P12=PH'

Update equation is meant to be:

P = P-KHP or P = (I-KH)P

As far I can figure:

P12' =/= HP (P12'=HP')

and so;

% P = P-K*P12'; is incorrect?

Raja Sekhar BandaruMohammad HoqueI am trying to estimate SOC of lithium-ion battery cell of 3.7 V_nominal, and 15.5 Ah in real time using extended Kalman filter (EKF). I am facing the problem to write MATLAB code for EKF with the noise covariance and other measurement and observation noises terms. How can I solve this problem in estimating SOC of li-ion battery. I am using MATLAB R2014a.

Hu LipingHi Ali,

Please have a look at the measurement equation. It only meatures the first state.

najib valiyffHi, I still get the Maximum recursion limit of 500 reached. Use

set(0,'RecursionLimit',N) to change the limit. Be

aware that exceeding your available stack space

can crash MATLAB and/or your computer.

Error in

ekf>create@(x)[x(2);x(3);0.05*x(1)*(x(2)+x(3))]

Message. Please help I've tried everything mentioned below including copy and pasting into command window

ailu wangSimon LevyNice work, Yi Cao! I used your code to understand the EKF, and I linked to it in an interactive online tutorial:

http://home.wlu.edu/~levys/kalman_tutorial

huaI want to learn how to use EKF

usdb usdb1hello; I have to do EKF with Matlab/simulink;could someone help me?

AliSomehow only the first state is tracked correctly. The estimate of x(2) and x(3) is always almost zero no matter how I change the model. Clearly there is a bug...

HienHi everybody!

I really have not understood this code yet. In my case, I also study on EKF for GPS data that I want to apply EKF to due with noise and missing data in GPS data. I have one GPS data columm with more than 2000 of length. Who could show me how to do it?

Thank you so much for your kinds

Ahmed Smatisehr gut!

VictorLines 51 and 53 are given by:

[x1,A]=jaccsd(fstate,x);

[z1,H]=jaccsd(hmeas,x1);

Why is x1 = fstate(x) used as the input for calculating the jacobian of the measurement equation? It makes more sense if the jacobian of the measurement equation is also evaluated at the current state x. Am I interpreting that part incorrectly?

usdb usdb1when i highlith error between variable and its estimate (by adding a new variable err=x-xestimate) i plot err. a cycle limit (oscillation )is in this figure.and a gap appear between variable and its estimate .

is it an explanation and solution to this.

DanHello everybody,

i have more general question about the extended kalman filter usage. what is not clear to me why EKF uses non-linear functions f and h for state prediction and estimate, while in other places the Jacobian of these functions is used.

Why the following is never used?

first calculate the liniarized state and measurements models at previous estimate point using Jacobian. Use the liniearized state transition and measurements matrix everywhere instead of non-linear in this specific iteration.

I would really appreciate your help

Thank you

M NGreat submission, thanks!

One question though: in the parameter explanation you define inputs x and P as "a priori" state estimate and "a priori" estimated state covariance. In my understanding this is not right, as "a priori" values are only available right after the prediction step of the filter.

So, in my opinion x and P are the "a posteriori" values of the previous time step. The "a priori" values of x and P of the current time step are available after the prediction step of your filter (vals x1 and P in lines 51 and 52).

Do you agree?

AlikoERROR!!!

Input argument "wstate" is undefined.

Error in ==> ekf at 51

[x1,A]=jaccsd(wstate,x); %nonlinear update and linearization at current state

ChinedumHi guys, i need some help please. I Use Matlab R2012b to try to run the code/example. I usually copy the whole code,place a new editor,highlight the example,right click,left click 'evaluate selection'(as i don't see any 'run').But on Matlab's command window, it shows the highlighted example and says "Undefined function 'ekf' for input arguments of type 'function_handle'." Please who knows what could be wrong? What could i be doing wrong? Thank you. John

usdb usdb1hi,

the states are well estimated by EKF,but if chaging in extended state variable at middle of the simulation EKF converdge always to the initial value one.

please i want explication.

Masiyang IslamMaria PerdomoHi,

Just one question:

why is the nonlinear update at line 51 done with out a numerical integration but just making the new x_k=f(x_k-1)?

W. Chongmohamedplease someone explain what these lines do from line 51 to line 78

Maria Perdomof is the nonlinear differential ecuation to be integrated, thats why the @ so that the ekf funtion can call it, an withing the ekf solve this ecuation to get the first estimation, the h is the measurement equation, also as handle function (@) so that it can be called by the ekf to calculate the kalman gain.

Tanmaycan someone explain what these lines do:

f=@(x)[x(2);x(3);0.05*x(1)*(x(2)+x(3))];

h=@(x)x(1);

Thanks!

tehreemwhat does the graph of 2nd and 3rrd state represent here

tehreem^^ please check your e-mail

Khan 954fstate in line 51 represents the non-linear state equations, which are function of x

in the example fstate is f, which is in line 26

tehreemwhat is fstate in line 51?

Khan 954@tehreem

the program is working well

copy the program from line 21 to line 46 and run it, its working

tehreemhi, im experiencing an error at line 51 and the program is not running due to that

can u please provide guidance in that regard

Olaf Gerritsedab483run the code as below in command window:

n=3

:

:

end

has an error:

??? Undefined function or method 'ekf' for input arguments of type

'function_handle'.

how to run these codes?

Simon OmekandaSimon OmekandaCan you go over the steps to properly run this function please?! I am still getting error that have been mentioned above in some comments, mainly:

??? Maximum recursion limit of 500 reached. Use set(0,'RecursionLimit',N)

to change the limit. Be aware that exceeding your available stack space can

crash MATLAB and/or your computer.

Error in ==> ekf>create@(x)[x(2);x(3);0.05*x(1)*(x(2)+x(3))]

Thanks:)

PrithwirajI downloaded the file and ran it on R2006b. Got the following error. Could someone tell me what I am doing wrong? I guess I have to uncomment a few things and run in some sequence, but unable to figure out what

??? Input argument "fstate" is undefined.

Error in ==> ekf at 51

[x1,A]=jaccsd(fstate,x); onlinear update and linearization at current state

ElkeHi;

I get the error message "??? Undefined function or method 'ekf' for input arguments of type 'function_handle'"

wawanthanks you

moisesHi!

Is there possible to use the code in a case where I have different rates of prediction and correction steps. (e.g., could I have 10 predictions before make one correction...). Is it easy to do this in the current version of the code?

George LimHi! This is a nice code for EKF. I have a question though: In your example if we assume that the value 0.05 is unknown parameter and we want simultaneous state and parameter estimation can we augment the state as with the parameter as:

n=4; %number of state

q=0.1; %std of process

r=0.1; %std of measurement

Q=q^2*eye(n); % covariance of process

% or Q=diag[Q 0]; % if no process noise is included in the parameter

R=r^2; % covariance of measurement

f=@(x)[x(2);x(3);x(4)*x(1)*(x(2)+x(3));x(4)]; % nonlinear state equations

h=@(x)x(1); % measurement equation

s=[0;0;1;0.1]; % initial state

x=s+q*randn(4,1); %initial state % initial state with noise

P = eye(n); % initial state covraiance

N=20; % total dynamic steps

xV = zeros(n,N); %estmate % allocate memory

sV = zeros(n,N); %actual

zV = zeros(1,N);

for k=1:N

z = h(s) + r*randn; % measurments

sV(:,k)= s; % save actual state

zV(k) = z; % save measurment

[x, P] = ekf(f,x,P,h,z,Q,R); % ekf

xV(:,k) = x; % save estimate

s = f(s) + q*randn(3,1); % update process

end;

Yi CaoMaria,

Yes, it is possible. Please look at the submission:

http://www.mathworks.com/matlabcentral/fileexchange/18289

Maria PerdomoHi, Is it possible to use your code for parameter identfication?

Krzysztofhi Yi

could you suggest an examplar definition of the function "f" together with initial state "s" for some real life example of a system? this would help me and other inexperienced guys to better understand this example. thank you very much in advance.

Big AndyChristy.hii..

when i run this program..the following error is displayed in the command window:

"??? Input argument "fstate" is undefined.

Error in ==> ekf at 51

[x1,A]=jaccsd(fstate,x); %nonlinear update and linearization at current state"

please rectify my problem asap...

Also suggest to me how to implement this code for multi sensor data fusion wherein the input is in the form of signals from n different sensors..as in how do I express my input here in terms of f and h.

DanielHi, how should I modify the m-file if I want to change the measurement- and process noise to:

w ~ N(u,Q)

v ~ N(e,R)

Matthew ColemanMatthew ColemanCongratulations. This is the first EKF library I manged to get working at all.

The example takes measurements go in the s matrix, not the x. Now that is fixed everything is good.

It is a long time since I did Kalman or Matlab. You clever guys underestimate how dumb you need to make your comments to get us newbies started.

Joao HenriquesYi CaoAeimit

Yes, it is possible. For example, see

http://www.mathworks.com/matlabcentral/fileexchange/18286

Yi

Aeimit LakdawalaIs it possible to do constrained nonlinear optimization with EKF?

iasri icarhi yi, would like to know if its appropriate to use EKF for forecasting of agricultural yields like fish ,rice etc. i am planning to use EXPAR with EKF for the problem stated above and would you kindly be able to give some of your ideas regarding the same.thankyou, with regards bishal.

maheswaran Rathinasamytimi wrote a very simple compound pendulum code, and some how this ekf algorithm does not work for that. only change that i had to do to that example file was change the states to 2 and rest

f=@(x)[x(2);-(g/l)*sin(x(1))];

this should give me sinusoidal waveform but it does not.

can you point out to me what could be wrong.

tim Heightsif in EKF i have to add state noise compensation, any good example or guidance here. how can i add to the example given by Yi Cao.

secondly, any one who could also recommend some book about it.

ChaoYi CaoFor continuous-time EKF, please look at http://www.mathworks.com/matlabcentral/fileexchange/18485

Rohit HippalgaonkarHi I am looking for an example where the EKF is applied to a continuous-time non-linear system with non-zero inputs (say measurements are taken at regular time samples through a non-linear (even linear would do) measurement process. I have looked around for this kind of example in the standard texts but haven't found any. Also a good source showing the implementation of the EKF wherein we linearize about a single operating point (as against linearizing about the predicted state every time) would be really helpful! Thanks in advance! Rohit

Dapat ChawahSorry, this comment is meant to be in the unscented kalman filter file discussion

Dapat ChawahThis code is working good for N<=150

but when N exceeds this limit, a nonsense happens

Is there any improvement to the code considering this error?

V. PoorYi CaoThis error occurs because you run the example incorrectly so that ekf calls itself more than 500 times. To run the example, you need copy contents between "%{" and "%}" then past it on matlab command window to execute the example.

It also could be because your MATLAB version is too old to support block comments. If that is the case, you can comment out all line by adding "%" at the begining of each line between "%{" and "%}" to solve the problem.

Zhongjie ChenHi, I still get the error

??? Maximum recursion limit of 500 reached. Use set(0,'RecursionLimit',N)

to change the limit. Be aware that exceeding your available stack space

can

crash MATLAB and/or your computer.

Error in ==> ekf>create@(x)[x(2);x(3);0.05*x(1)*(x(2)+x(3))]

after following your instructions. How do I correctly run the code?

maureen clercBeware: function ekf changes the value of the measurement covariance matrix R. It shouldn't be the case. Otherwise the code is nice and efficient.

Lihong WangNice code. But if there is load disturbance on the state, why the estimate from the EKF almost ignores the load disturbance?

Tim DavisExcellent! Nice use of CHOL instead of INV (as can be seen in two other Kalman-filter codes on the File Exchange). Nice to see good numerics at work.

I see that "K=P12*inv(...)" is commented out; that's perfect. It gives the math behind what the CHOL and backslashes are doing.

Saroj Pandeyit is very good and helpful in my project.

Neric LauVery helpful for learning Kalman Filter Implementation.

Dmitry ShNicely made, and very intuitive if one has an idea how a linear Kalman Filter works. However I found that numerically solving the Jacobian is not always the best form of linerisation, especially for simpler cases when an analytic Jacobian can be computed by hand.

In my experiments (with simple non-linear models) an analytic Jacobian usually gave a significant improvement of fit when compared to its numeric counterpart. Maybe you could add an option on how it should be solved

hu aijunfeng yumeng junvery well.

Reza BaghaeiTaher DERBELYi CaoDear Edwin,

As I expected, this error is due to your way to run the example because the error message shows that the error occures at line 19, which is a commented line to begin the example.

To correctly run the example, you can follow the following steps:

1. select the example lines correctly

2. press control-t to uncomment the selection

3. right-click to run the selection

4. click un-do to recover the file. (DO NOT click the save button.)

For you and other users' convenient, I updated the file with block-comment lines for the example. Now, you just need to select and right-click to run the example without change the file. The update will appear a few hours later.

Hope this help.

edwin de Vries??? Error: File: ekf.m Line: 19 Column: 10

Expression or statement is incomplete or incorrect.

??? Maximum recursion limit of 500 reached. Use set(0,'RecursionLimit',N)

to change the limit. Be aware that exceeding your available stack space can

crash MATLAB and/or your computer.

Error in ==> ekf>create@(x)[x(2);x(3);0.05*x(1)*(x(2)+x(3))] at 25

f=@(x)[x(2);x(3);0.05*x(1)*(x(2)+x(3))]; % nonlinear state equations

sayed mohammad mousavi gazafrudi