Trouble getting array to fill in properly
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
Simon Chan
le 17 Mar 2022
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 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!