Creating Diagonal Matrix from a Vector

19 次查看(过去 30 天)
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?

采纳的回答

Stephen23
Stephen23 2020-11-16
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

更多回答(3 个)

Ameer Hamza
Ameer Hamza 2020-11-16
编辑:Ameer Hamza 2020-11-16
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
Bruno Luong 2020-11-16
编辑:Bruno Luong 2020-11-16
>> 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
KSSV 2020-11-16
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

类别

Help CenterFile Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by