简体   繁体   中英

how to find upper and lower diagonal matrix matlab

I tried to use matlab to find the upper and lower diagonal matrix in matlab

here is the idea

if I have matrix 4x4

 1  2  3  4 
 5  6  7  8
 9 10 11 12 
13 14 15 16

the main diagonal is

1 6 11 16

but the second upper diagonal is

2 7 12

and the lower is

5 10 15

so there is triu and tril but to to write it or use any other function in matlab to find this upper and lower diagonal in matrix.

just use diag , for example

 diag(A,0)   % main diagonal, also diag(A)
 diag(A,-1)  % lower diagonal
 diag(A,1)   % upper ...

You can use simple linear indexing to get any diagonal of a matrix. All you need to know is the linear index of the first element and the number of rows in the matrix:

 >> [m n] = size(A);

Get the main diagonal on the matrix (first element index is 1):

 >> A( 1 : ( m+1 ) : end )

Get the lower diagonal (first index is 2):

 >> A( 2 : ( m+1 ) : end )

Get the upper diagonal (first index is m+1 ):

>> A( (m+1) : (m+1) : end )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM