Effective matrix defining (diagonals)

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

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

@Nitzan Haviv: my pleasure! Remember to click the accept button if my answer helped you!

Sign in to comment.

More Answers (1)

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

Products

Tags

Community Treasure Hunt

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

Start Hunting!