Generate a diagonal matrix from the elements of another matrix

조회 수: 14 (최근 30일)
Marco
Marco 2020년 1월 25일
댓글: Marco 2020년 1월 25일
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

채택된 답변

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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by