Creating Diagonal Matrix from a Vector
3 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
Stephen23
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])
0 Comments
More Answers (3)
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
0 Comments
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)]);
0 Comments
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
0 Comments
See Also
Categories
Find more on Operating on Diagonal Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!