diag has this functionality built in:
diag(ones(4,1),1)
ans =
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
0 0 0 0 0
diag(ones(4,1),-1)
ans =
0 0 0 0 0
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
Where the syntax of diag(V,k)
is: V
is the vector to be put on the diagonal (be it ones, or any odd vector), and k
is the label of the diagonal. 0
is the main diagonal, positive integers are increasingly further away upper diagonals and negative integers the same for the lower diagonals; i.e. k=1
gives the first upper diagonal, k=-4
gives the lower left corner in this example.
For completeness, if you just want the indices instead of a full matrix (since you suggested you wanted to insert a vector into a present matrix) you can use the following function:
function [idx] = diagidx(n,k)
% n size of square matrix
% k number of diagonal
if k==0 % identity
idx = [(1:n).' (1:n).']; % [row col]
elseif k>0 % Upper diagonal
idx = [(1:n-k).' (1+k:n).'];
elseif k<0 % lower diagonal
idx = [(1+abs(k):n).' (1:n-abs(k)).'];
end
end
where each row of idx
contains the indices for the matrix.