Index exceeds matrix dimensions error
2 ビュー (過去 30 日間)
古いコメントを表示
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
0 件のコメント
回答 (2 件)
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.
0 件のコメント
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.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!