Generate a diagonal matrix from the elements of another matrix

13 views (last 30 days)
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

Accepted Answer

Akira Agata
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
  1 Comment
Marco
Marco on 25 Jan 2020
It works perfectly! Thanks and sorry for wasting your time on such an easy question.

Sign in to comment.

More Answers (0)

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!