Effective matrix defining (diagonals)

2 views (last 30 days)
hi, i would like to get some help with defining the next matrix in the easiest way. i know the diag() function but i didnt find a way the define the non-main diagonals.

Accepted Answer

Stephen23
Stephen23 on 4 Aug 2021
N = 7;
M = toeplitz([-2,1,zeros(1,N-2)])
M = 7×7
-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 0 0 0 1 -2 1 0 0 0 0 0 1 -2 1 0 0 0 0 0 1 -2
  2 Comments
Stephen23
Stephen23 on 4 Aug 2021
@Nitzan Haviv: my pleasure! Remember to click the accept button if my answer helped you!

Sign in to comment.

More Answers (1)

Nitzan Haviv
Nitzan Haviv on 4 Aug 2021
btw i found another way
when N is the dimention of the square matrix
d_sec = ones(1,N-1);
d_main= ones(1,N).*-2;
H = diag(d_main)+diag(d_sec,-1) + diag(d_sec,1);

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!