You are looking for spdiags
:
>> n = 6; m = n-2;
>> D = full(spdiags(-2*ones(m,1),0,m,n))
D =
-2 0 0 0 0 0
0 -2 0 0 0 0
0 0 -2 0 0 0
0 0 0 -2 0 0
Or just use eye
:
D = -2*eye(m,n)
Perhaps you want to combine several diagonals:
>> B = [ones(m,1) -2*ones(m,1) ones(m,1)];
>> D = full(spdiags(B,0:2,n-2,n))
D =
1 -2 1 0 0 0
0 1 -2 1 0 0
0 0 1 -2 1 0
0 0 0 1 -2 1