Index exceeds matrix dimensions error

조회 수: 1 (최근 30일)
Nicholas Boccella
Nicholas Boccella 2017년 10월 12일
답변: Christine Tobler 2017년 10월 12일
I'm writing a code where one inputs a matrix M, and then I have a function that performs LU Decomposition on it. Then, I have this code, which performs forward substitution Ly=b and then uses y to solve Ux=y. When I run the code with a 3x3 matrix it works fine, but for a 5x5 matrix I got the error "Index exceeds matrix dimension." with line 11 that says sum=b(i); and I'm not sure what I am doing wrong. Any help would be great! Also, apologize formatting is a bit off, but i promise it is correct in matlab and not why code won't run.
function x=forwardsolve(L,U,b)
%perform forward substitution on a lower triangular matrix L to solve Ly=b
%perform back substitution on an upper triangular matrix U to solve Ux=y
[m,n]=size(L);
y=zeros(n,1);
y(1)=b(1)/L(1,1);
for i=2:1:n
sum = b(i);
for j=1:i-1
sum = sum-L(i,j)*y(j);
end
y(i)=sum/L(i,i);
end
[m,n]=size(U);
x=zeros(n,1);
x(n)=y(n)/U(n,n);
for i=n-1:-1:1
sum = y(i);
for j=i+1:n
sum = sum-U(i,j)*x(j);
end
x(i)=sum/U(i,i);
end
end

답변 (2개)

James Tursa
James Tursa 2017년 10월 12일
편집: James Tursa 2017년 10월 12일
Did you remember to give it a 5-element b vector, or did you inadvertently give it the old 3-element b vector? I tried your code with a 5x5 system and it appeared to work, giving the same result as the backslash operator.

Christine Tobler
Christine Tobler 2017년 10월 12일
With index out of bounds errors, in can be useful to do the following: >> dbstop on error >> ... run your code ... When the error happens, the debugger is brought to the line at which the error happens, so you can look at the values of the indices to see what the problem is. Once you've fixed the problem, remember to use |dbclear on error| to get out of this mode.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by