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

2 views (last 30 days)
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 Comments
JONATHAN NEMARIAM
JONATHAN NEMARIAM on 19 Mar 2019
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

Sign in to comment.

Answers (1)

Andrei Bobrov
Andrei Bobrov on 19 Mar 2019
Edited: Andrei Bobrov on 19 Mar 2019
A = gallery('tridiag',100,-1,2,-1);
or
n = 100;
A = spdiags(ones(n,1)*[-1 2 -1],-1:1,n,n);

Categories

Find more on Operating on Diagonal Matrices 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!