How to ensure Matrixes are matching size

조회 수: 5 (최근 30일)
William
William 2025년 5월 1일
댓글: Walter Roberson 2025년 5월 2일
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
Walter Roberson
Walter Roberson 2025년 5월 1일
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 2025년 5월 1일
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

댓글을 달려면 로그인하십시오.

답변 (1개)

Walter Roberson
Walter Roberson 2025년 5월 1일
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
William
William 2025년 5월 2일
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 2025년 5월 2일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Array Geometries and Analysis에 대해 자세히 알아보기

태그

제품


릴리스

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by