Index exceeds matrix dimensions error

2 ビュー (過去 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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by