Hello, I am receiving an error when attempting to build a matrix. The error and the code is pasted below.

%% One dimensional Kalman Filter demonstration. % Initialise the variables clear all; clc; clf; XEst=0; RNoise=0.1; ErrorCov=1; XEst=zeros(1,10)
%The ZedK are the actual measurements that were taken ZedK=[.39 .5 .48 .29 .25 .32 .34 .48 .41 .45];
%% This section describes the Kalman calculations, note that for the one dimension we do not have to deal with arrays
for k=1:10
%Time Update predictor equations
XPriorEst=XEst;
P_ErrorCov=ErrorCov;
%Measurement Update corrector equations
KGain=P_ErrorCov/(P_ErrorCov+RNoise);
XEst(k)=(XPriorEst+KGain*((ZedK(:,k))-XPriorEst))% Here I am building the XEst to plot.
ErrorCov=(1-KGain)*P_ErrorCov;
end
plot(XEst)
The error that I receive is as follows
In an assignment A(I) = B, the number of elements in B and I must be the same.
Error in AndrewKalman1D (line 25) XEst(k)=(XPriorEst+KGain*((ZedK(:,k))-XPriorEst))% The XEst is attempting to be being populated here,
>>

Answers (1)

In the line
XPriorEst=XEst;
the variable 'XPriorEst' is made equal to an entire 1x10 array. When it is used in the line
XEst(k) = (XPriorEst+KGain*((ZedK(:,k))-XPriorEst))
the right side of the assignment is therefore also 1x10, but you are attempting to put that into the scalar value XEst(k). Matlab doesn't know how to accomplish that. This is exactly what your error message has told you.
Probably you meant to write
XPriorEst=XEst(k);
in that previous line.

2 Comments

Thankyou for your prompt reply, the code does work when I do this, however the answers yielded from XEst are now incorrect. They appear to be affected by the pre-allocation. The formulas are correct because if I run the code recalculating XEst every time (ie, not building the array by using (k) the results are as expected. I cannot turn off the pre-allocation because I then get an out of bounds error. If I run the code as follows,
%% One dimensional Kalman Filter demonstration. % Initialise the variables clear all; clc; clf; XEst=0; RNoise=0.1; ErrorCov=1; %XEst=zeros(1,10);
%The ZedK are the actual measurements that were taken ZedK=[.39 .5 .48 .29 .25 .32 .34 .48 .41 .45];
%% This section describes the Kalman calculations, note that for the one dimension we do not have to deal with arrays
for k=1:10;
%Time Update predictor equations
XPriorEst=XEst;
P_ErrorCov=ErrorCov;
%Measurement Update corrector equations
KGain=P_ErrorCov/(P_ErrorCov+RNoise);
XEst=(XPriorEst+KGain*((ZedK(:,k)) - XPriorEst))% Here I am building the XEst to plot.
ErrorCov=(1-KGain)*P_ErrorCov;
end
plot(XEst)
then the list shown by the 10 XEst outputs is exactly what I want to plot. I am not sure how to deal with this from here.
Thanks in advance for your help.
Andrew

Sign in to comment.

Asked:

on 29 Mar 2014

Commented:

on 30 Mar 2014

Community Treasure Hunt

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

Start Hunting!