Generate a diagonal matrix from the elements of another matrix
13 views (last 30 days)
Show older comments
Good morning, I'm trying to generate a diagonal matrix with non-zero elemets from another matrix.
For example I have a general matrix like: (usually it's around 40x5)
A=[1 2 3 4 5;
6 7 8 9 10];
I would like to generate a matrix with the elements of A on the diagonal, just like:
1 0 0 0 0 0 0 0 0 0
0 2 0 0 0 0 0 0 0 0
0 0 3 0 0 0 0 0 0 0
0 0 0 4 0 0 0 0 0 0
0 0 0 0 5 0 0 0 0 0
0 0 0 0 0 6 0 0 0 0
And so on untili 10.
Can someone help me?
Thanks in advance
0 Comments
Accepted Answer
Akira Agata
on 25 Jan 2020
I would recommend using diag function.
The following is an example:
A = [1 2 3 4 5;
6 7 8 9 10];
A = A';
output = diag(A(:));
>> output
output =
1 0 0 0 0 0 0 0 0 0
0 2 0 0 0 0 0 0 0 0
0 0 3 0 0 0 0 0 0 0
0 0 0 4 0 0 0 0 0 0
0 0 0 0 5 0 0 0 0 0
0 0 0 0 0 6 0 0 0 0
0 0 0 0 0 0 7 0 0 0
0 0 0 0 0 0 0 8 0 0
0 0 0 0 0 0 0 0 9 0
0 0 0 0 0 0 0 0 0 10
More Answers (0)
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!