Adding numbers to specific matrix index.

14 views (last 30 days)
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

Accepted Answer

Geoff Hayes
Geoff Hayes on 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?

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!