# Creating Diagonal Matrix from a Vector

1 view (last 30 days)
Piyush Gupta on 16 Nov 2020
Answered: KSSV on 16 Nov 2020
I have a vector g = [g0 g1 g2 g3 ... gx]
I want to create a matrix of the form:
Here x = (m-n)
Any thoughts on how I can do this?

Stephen Cobeldick on 16 Nov 2020
The efficient MATLAB approach:
g = [1,2,3,4,5];
z = zeros(1,numel(g)-1);
m = toeplitz([g(1),z],[g,z])
m = 5×9
1 2 3 4 5 0 0 0 0 0 1 2 3 4 5 0 0 0 0 0 1 2 3 4 5 0 0 0 0 0 1 2 3 4 5 0 0 0 0 0 1 2 3 4 5

Ameer Hamza on 16 Nov 2020
Edited: Ameer Hamza on 16 Nov 2020
This is one way
g = [1 2 3 4 5];
n = numel(g);
M_ = [eye(n) zeros(n,n-1)];
M = zeros(n, 2*n-1);
for i = 1:n
M = M + circshift(M_*g(i), i-1, 2);
end
Result
>> M
M =
1 2 3 4 5 0 0 0 0
0 1 2 3 4 5 0 0 0
0 0 1 2 3 4 5 0 0
0 0 0 1 2 3 4 5 0
0 0 0 0 1 2 3 4 5

Bruno Luong on 16 Nov 2020
Edited: Bruno Luong on 16 Nov 2020
>> g=[1 2 3]
g =
1 2 3
>> p=length(g);
>> s=10;
>> A=full(spdiags(repmat(g,s,1),0:p-1,s,s+p-1))
A =
1 2 3 0 0 0 0 0 0 0 0 0
0 1 2 3 0 0 0 0 0 0 0 0
0 0 1 2 3 0 0 0 0 0 0 0
0 0 0 1 2 3 0 0 0 0 0 0
0 0 0 0 1 2 3 0 0 0 0 0
0 0 0 0 0 1 2 3 0 0 0 0
0 0 0 0 0 0 1 2 3 0 0 0
0 0 0 0 0 0 0 1 2 3 0 0
0 0 0 0 0 0 0 0 1 2 3 0
0 0 0 0 0 0 0 0 0 1 2 3
% This work as well
>> A = toeplitz([g(1) zeros(1,s-1)],[g zeros(1,s-1)]);

KSSV on 16 Nov 2020
g = rand(1,4) ;
m = length(g) ;
P =zeros(m) ;
d=size(diag(P,i),1);%this is the size of the vector with elements of the kth diagonal
for i = 1:m
e=g(i)*ones(m+1-i,1);
P = P+diag(e,i-1);
end