How do I specify the diagonal elements of a matrix?
Show older comments
I have some values, taken from another matrix. How do I specify them to be the diagonals of a new matrix?
1 Comment
Hassan Rezaee
on 19 Aug 2016
You may use the function spdiags
Answers (2)
Matt Tearle
on 13 Feb 2011
To do a subscripted assignment into the diagonal of a matrix, you can use linear indexing:
A(1:n+1:end) = v
(where v is an n-element vector and n is the number of rows of A). So, for example,
A(1:n+1:end) = diag(B)
copies the diagonal of B into A.
5 Comments
Changyong He
on 25 Dec 2017
I do not know why there is no comment. I have to say that it is the easiest way I have found. Excellent!
Image Analyst
on 25 Dec 2017
Another way (again assuming you know n already):
A(logical(eye(n))) = diag(B)
Dominick Arturi
on 5 Mar 2020
This works great for foward diagonals but how would one go about doing this to acess backwards diagonals?
Walter Roberson
on 5 Mar 2020
n:n-1:end-n+1 for backwards diagonal on a square matrix
Sebastien de Kort
on 11 Sep 2020
A(logical(fliplr(eye(n)))) = diag(B)
Bruno Luong
on 13 Feb 2011
Take a look at DIAG function
help diag
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!