MATLAB: How to full fill the diagonal of a matrix by a vector

circshiftdiagonal matrix

hello
how can i full fill a matrix (17*9) by a vector by length 9
for example i have the vector d=[1 2 3 ] and the matrix zeros(5*5) and i want to make the output matrix like this
1 0 0 3 2
2 1 0 0 3
3 2 1 0 0
0 3 2 1 0
0 0 3 2 1
thanks

Best Answer

This approach uses circshift() to circularly shift the columns of matrix.
m = zeros(5,5);
v = [1,2,3];
% Loop through each column of m
for i = 1:size(m,2)
m(1:length(v),i) = v;
m(:,i) = circshift(m(:,1), i-1);
end
Result:
m =
1 0 0 3 2
2 1 0 0 3
3 2 1 0 0
0 3 2 1 0
0 0 3 2 1