Generate a diagonal matrix from the elements of another matrix

14 visualizaciones (últimos 30 días)
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

Respuesta aceptada

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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Operating on Diagonal Matrices en Help Center y File Exchange.

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by