Index exceeds the number of array elements (1)

조회 수: 2 (최근 30일)
Yago Ferrara Román
Yago Ferrara Román 2021년 10월 20일
댓글: Jan 2021년 10월 21일
I`m trying to do a function to solve a lower triangular matrix but whe I try to run the code, it says there's a problem.
function [x]=sistriinferior(U,b,n)
x(1) = b(1)/U(1,1);
for i=2:n
s=0;
for j=1:n-1
s= s + U(i,j)*x(j); %apparently the problem is in this line
end
x(i) = (b(i)-s)/U(i,i);
end
end

채택된 답변

Jan
Jan 2021년 10월 20일
편집: Jan 2021년 10월 20일
Replace
for j = 1:n-1
by
for j = 1:i-1
By the way, you can write
s = 0;
for j = 1:i - 1
s = s + U(i, j) * x(j);
end
as
s = U(i, 1:i - 1) * x(1:i - 1); % Dot product
Preallocate the output x before the loop to avoid the very expensive iterative growing of arrays:
x = zeros(n, 1);
  댓글 수: 2
Yago Ferrara Román
Yago Ferrara Román 2021년 10월 20일
Thank you so much, I'm starting to use this program at college and I have zero experience
Jan
Jan 2021년 10월 21일
Do you know Matlab Onramp? This is a useful tutorial.
The debugger helps also to examine what's going on: Set a breakpoint on the left side of the editor. Then you can step through the code line by line during it is processed and control the values of the used variables.
Mistakes like the exchanged index in your case are hard to find, because your brain knows, what you wanted to type. This impedes the reading psychologically. In such cases it is the best option to ask colleagues, who are not involved or foreigners of the forum, who see the problem in a second. :-)

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by