Unable to perform assignment because the left and right sides have a different number of elements.

3 views (last 30 days)
I used this code for perfoming kalman filtering for signal data. the measurment are random created.
this massege was appearing (Unable to perform assignment because the left and right sides have a
different number of elements.)
% %Initializations
Pk_prev = [0,0; 0,0];
x_kprev_hat = [0 ; 0];
xk_hat = [];
% Time update equations
A= [0.5 , 0 ; 0 , 0.3];
B = 0;
% Measurement update equations
H = [ 1 , 0];
z = rand(2,200);
E_x=[1,0 ; 0,1]; %Simulating noisy measurements
E_s =[1,0 ; 0,1];
E_y=1
%Measurement model
z_k = H*(z + 1) + E_y;
P = zeros(1,length(z));
% Measurement noise
R =1;%R = 0.000001 for a very low value
% Process noise covariance
Q =[1, 0; 0, 1];
for k = 1: length(z)
x_k_hat_minus = A*x_kprev_hat+ E_x ; %a priori estimate
Pk_minus = A*Pk_prev * A'+ Q; %A priori estimate error covariance
Kk = Pk_minus/(Pk_minus + R);%Kalman gain
x_kprev_hat = x_k_hat_minus + Kk*(z_k(k) - x_k_hat_minus); %A priori estimate
xk_hat = cat(2,xk_hat,x_kprev_hat);%A posteriori estimate
Pk_prev = (1 - Kk)*Pk_minus;%A posterirori estimate error covariance
P(k) = Pk_prev;
end
plot(z_k,'bx-');
hold on;
plot(xk_hat,'gx-');
plot(z*ones(1,200),'rx-');
figure;
plot(P,'r');
E_y =1

Accepted Answer

Star Strider
Star Strider on 9 May 2019
The ‘Pk_prev’ variable is a (2x2) matrix. You cannot assign that to a scalar array element in ‘P’.
If you preallocate ‘P’ as:
P = zeros(2,2,length(z));
and then assign it as:
P(:,:,k) = Pk_prev;
your code works. You then need to plot ‘z’ as:
plot(z,'rx-');
Plotting ‘P’ however is not possible with your current code.
You can plot it with this:
figure
hold all
for k = 1:size(P,3)
surf(P(:,:,k))
end
hold off
grid on
view(-30,30)
Experiment to get the result you want.
  5 Comments
Star Strider
Star Strider on 19 May 2019
I cannot follow what you are doing.
I have no suggestions on how to make your code produce the plot you expect.

Sign in to comment.

More Answers (1)

Alex Mcaulley
Alex Mcaulley on 9 May 2019
Running your code, it throws an error in this line
P(k) = Pk_prev;
The problem is that PK_prev is of size 2x2 and P is 1x200, then the assignment is incorrect.

Community Treasure Hunt

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

Start Hunting!