How to ensure Matrixes are matching size

2 views (last 30 days)
William
William on 1 May 2025
Commented: Walter Roberson on 2 May 2025
I am doing a recursive least squares model to try and reduce sensor error for a project, but I keep getting the error that the left and right matrixes in the for loop are mismatched- the left is 4- by 1 and the right is 4 by four, and I'm not sure where it's going wrong, or how to fix it.
function [Qhat]= RLS_estimation(Z,Unite,T) %
% Call A matrix from gen sate, final matrix
n=0;
P(:,:,1)=eye(4);
R=fixed.forgettingFactor(Z);
A=[1,T,0,0;0,1,0,0;0,0,1,T;0,0,0,1];
K = zeros(4, 1,n);
% AT is otranspose A, transpose A here
% Call matrix R with 'forgetting factors"
Qhat(:,:,1)=Unite;
for n= 2:Z
K(:,:,n)=P(:,:,n-1)*A.'*inv(A*P(:,:,n-1)*A.'+R);
P(:,:,n)=inv(R)-K(:,:,n)*A*inv(R)*P(:,:,n-1);
Qhat(:,:,n)=Qhat(:,:,n-1)+K(:,:,n)*(Unite(n)-A*Qhat(:,:,n-1));
end
  2 Comments
Walter Roberson
Walter Roberson on 1 May 2025
We do not know the size of Z or Unite or T (though we can deduce that T must be scalar)
You did not indicate which line the problem is occuring on.
William
William on 1 May 2025
The problem is occuring on the first line of the for loop, where we calculate K for a given N value. Though I belive it may occur for the next two lines as well.
T is a scalar between one and zero, Z is a scalar, which was 60 when I was getting this error.
Unite is a four by Z matrix

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 1 May 2025
K = zeros(4, 1,n);
K is initialized to 4 x 1 by something.
K(:,:,n)=P(:,:,n-1)*A.'*inv(A*P(:,:,n-1)*A.'+R);
P is 4 x 4 by something.
A is 4 x 4.
P(:,:,n-1) * A.' is 4 x 4 x 1 mtimes transpose(4 x 4) so that part is (4 x 4) * (4 x 4) which gives a 4 x 4 result.
inv(A etc) is inv() of 4 x 4, so is 4 x 4 itself.
(4 x 4) * (4 x 4) gives a 4 x 4 result.
So the right hand side is 4 x 4.
You are attempting to store the 4 x 4 into a space that has been declared to be 4 x 1 x (1) . It is not going to fit.
Everything appears to work out if you initialized
K = zeros(4, 4,n);
  2 Comments
William
William on 2 May 2025
This appears to work, but when I attempt to plot it, everything goes fine until the line for this matrix, shown in red, goes back on itself.
Everthing else about the plot looks good, though.
Walter Roberson
Walter Roberson on 2 May 2025
Unite is a four by Z matrix
But your code has
Qhat(:,:,n)=Qhat(:,:,n-1)+K(:,:,n)*(Unite(n)-A*Qhat(:,:,n-1));
which uses Unite as if it is a vector.

Sign in to comment.

Tags

Products


Release

R2024a

Community Treasure Hunt

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

Start Hunting!