Adding numbers to specific matrix index.

29 vues (au cours des 30 derniers jours)
Mr.Tentacles
Mr.Tentacles le 6 Mar 2019
Commenté : Mr.Tentacles le 6 Mar 2019
i want to fill in a 100x100 matrix using a nested for loop. However for each ’i’ row there will only be 3 ‘j’ columns with nonzero numbers. Also i want leave the first and last row all zeros. This is what ive tried before and its not working. what am i doing wrong?
A = zeros(100,100);
h = 1;
for i = 2:99;
for j = 2:99;
A(i, j+1) = ((1/h) + i);
A(i, j) = (-2/h);
A(i, j-1) = ((1/h) - i);
end
end
%so after one iteration i would have the values at the given indices
% %A(2,3) = 3
%A(2,2)=-2
%A(2,1)=-1

Réponse acceptée

Geoff Hayes
Geoff Hayes le 6 Mar 2019
However for each ’i’ row there will only be 3 ‘j’ columns with nonzero numbers How do you determine which three columns of the ith row are non-zero? In your above example, for the second row, the first three elements are non-zero. Does this mean that in the third row, the 2-4 columns are non-zero? In which case you would do something like
A = zeros(100,100);
h = 1;
for i = 2:99;
A(i, i+1) = ((1/h) + i);
A(i, i) = (-2/h);
A(i, i-1) = ((1/h) - i);
end
Or are you trying to do something else?
  1 commentaire
Mr.Tentacles
Mr.Tentacles le 6 Mar 2019
yes this works thanks you

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by