How to make the main diagonal and the diagonal above and below the main diagonal equal to -2 and 1 respectively

12 ビュー (過去 30 日間)
Hi, I have a NxN matrix (N=100) how can I make it so that the main diagonal is -2 and the diagonal above and below the main is 1? and everything else is 0? thanks!
  3 件のコメント
JONATHAN NEMARIAM
JONATHAN NEMARIAM 2019 年 3 月 19 日
Well the matrix would be 100x100, so the diagonal would be -2 and ONLY the diagonal above and below the main will be 1, so everything else will be a 0.
[-2 1 0 0 0 0 0
1 -2 1 0 0 0 0
0 1 -2 1 0 0 0
0 0 1 -2 1 0 0] and so on to where it's 100x100
Takumi
Takumi 2019 年 3 月 19 日
編集済み: Takumi 2019 年 3 月 19 日
N = 100;
A = -2*eye(N) + diag(ones(1,N-1),1) + diag(ones(1,N-1),-1);

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

回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2019 年 3 月 19 日
編集済み: Andrei Bobrov 2019 年 3 月 19 日
A = gallery('tridiag',100,-1,2,-1);
or
n = 100;
A = spdiags(ones(n,1)*[-1 2 -1],-1:1,n,n);

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by