Adding numbers to specific matrix index.

28 Ansichten (letzte 30 Tage)
Mr.Tentacles
Mr.Tentacles am 6 Mär. 2019
Kommentiert: Mr.Tentacles am 6 Mär. 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

Akzeptierte Antwort

Geoff Hayes
Geoff Hayes am 6 Mär. 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?

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by