MATLAB: Is there a way to assign a value to multiple diagonals in a matrix

diagonalsmatrix manipulation

I'm trying to create a matrix to later solve, and the matrix should basically be a zeros matrix of whatever size with the middle 3 diagonals assigned to three different values- .1, -2, and 5. Is this possible and how would I do it?

Best Answer

E.g., for a square matrix:
>> X = zeros(6,6)
X =
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
>> m = size(X,1)
m =
6
>> X(1:m+1:end) = 1 % main diagonal
X =
1 0 0 0 0 0
0 1 0 0 0 0
0 0 1 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1
>> X(2:m+1:end) = 2 % lower diagonal
X =
1 0 0 0 0 0
2 1 0 0 0 0
0 2 1 0 0 0
0 0 2 1 0 0
0 0 0 2 1 0
0 0 0 0 2 1
>> X(m+1:m+1:end) = 3 % upper diagonal
X =
1 3 0 0 0 0
2 1 3 0 0 0
0 2 1 3 0 0
0 0 2 1 3 0
0 0 0 2 1 3
0 0 0 0 2 1
Or, using spdiags:
>> m = 6
m =
6
>> X = full(spdiags(bsxfun(@times,ones(m,1),[2 1 3]),[-1 0 1],m,m))
X =
1 3 0 0 0 0
2 1 3 0 0 0
0 2 1 3 0 0
0 0 2 1 3 0
0 0 0 2 1 3
0 0 0 0 2 1