Adding numbers to specific matrix index.

30 ビュー (過去 30 日間)
Mr.Tentacles
Mr.Tentacles 2019 年 3 月 6 日
コメント済み: Mr.Tentacles 2019 年 3 月 6 日
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

採用された回答

Geoff Hayes
Geoff Hayes 2019 年 3 月 6 日
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 件のコメント
Mr.Tentacles
Mr.Tentacles 2019 年 3 月 6 日
yes this works thanks you

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by