Trouble getting array to fill in properly
조회 수: 1 (최근 30일)
이전 댓글 표시
I am trying to fill in a tridiagonal 8x8 array using a for loop. I believe that most of the array is flling in properly, but there are four of the array numbers that are being filled in as zero and I can't figure out how to fix it. This is the code that I have for it so far.
x = [0.06 0.47 1.01 1.50 2.05 2.53 2.99 3.44];
y = [1.0499 1.3274 1.3588 1.2550 1.6322 2.5523 3.4462 3.6684];
z = linspace(x(1),x(end),1000);
n = length(x)-1;
h = zeros(n,1);
A = zeros(n+1,n+1);
for i=1:n
h(i)=x(i+1)-x(i);
end
for i=2:n
for k=2:n
if i==k
A(i,k)=2*(h(i-1)+h(i));
elseif (k+1)==i
A(i,k)=h(i-1);
elseif (k-1)==i
A(i,k)=h(i);
else
A(i,k)=0;
end
end
A(1,1)=1;
A(n+1,n+1)=1;
end
The problem that I am having is the I think there is something wrong with the code that prevents it from properly filling in A(1,2) A(2,1) A(7,8) and A(8,7), but I don't know what would cause that to happen, this is the matrix that I am getting when I run this, and you can see that the corners of the matrix aren't filled in correctly.
A =
1.0000 0 0 0 0 0 0 0
0 1.9000 0.5400 0 0 0 0 0
0 0.5400 2.0600 0.4900 0 0 0 0
0 0 0.4900 2.0800 0.5500 0 0 0
0 0 0 0.5500 2.0600 0.4800 0 0
0 0 0 0 0.4800 1.8800 0.4600 0
0 0 0 0 0 0.4600 1.8200 0
0 0 0 0 0 0 0 1.0000
댓글 수: 0
답변 (1개)
Simon Chan
2022년 3월 17일
The for loop starts from 2 to n, which is 7 in your case.
However, the matrix has 8 rows and 8 columns and hence you never touch the first column, first row, last column and last row in the loop.
At the end, you just fill in the following two values and hence it appears in the output. (Actually no need to put these 2 lines inside the for loop)
A(1,1)=1;
A(n+1,n+1)=1;
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!