主要内容

diag

创建对角矩阵或对角线的元素matrix

Description

example

d = diag(v)returns a square diagonal matrix with the elements of vectorvon the main diagonal.

example

d = diag(v,k)places the elements of vectorvon thekth diagonal.k=0represents the main diagonal,K> 0is above the main diagonal, andk<0is below the main diagonal.

example

x = diag(A)返回主要对角线元件的列矢量A

example

x = diag(A,k)returns a column vector of the elements on thekth diagonal ofA

Examples

collapse all

Create a 1-by-5 vector.

V = [2 1 -1 -1 -2 -5];

利用diagto create a matrix with the elements ofvon the main diagonal.

d = diag(v)
d =5×52 0 0 0 0 0 0 0 0 0 0 0 0 0-1 0 0 0 0 0 0-2 0 0 0 0 0 0 -5

创建一个与元素的矩阵von the first super diagonal (k=1).

D1 =diag(v,1)
D1 =6×60 2 0 0 0 0 0 0 1 0 0 0 0 0 0 -1 0 0 0 0 0 0 -2 0 0 0 0 0 0 -5 0 0 0 0 0 0

这result is a 6-by-6 matrix. When you specify a vector of lengthn作为输入,diagreturns a square matrix of sizeN+ABS(K)

Get the elements on the main diagonal of a random 6-by-6 matrix.

A = randi(10,6)
A =6×69 3 10 8 7 8 10 6 5 10 8 1 2 10 9 7 8 3 10 10 2 1 4 1 7 2 5 9 7 1 1 10 10 10 2 9
x = diag(A)
x =6×19 6 9 1 7 9

获取第一个分子的元素(k=-1) ofA。这result has one fewer element than the main diagonal.

x1 = diag(A,-1)
x1 =5×110 10 2 9 2

Callingdiag两次返回由原始矩阵的对角线元素组成的对角矩阵。

A1 = diag(diag(A))
A1 =6×69 0 0 0 0 0 0 6 0 0 0 0 0 0 9 0 0 0 0 0 0 1 0 0 0 0 0 0 7 0 0 0 0 0 0 9

Input Arguments

collapse all

Diagonal elements, specified as a vector. Ifvis a vector withNelements, thendiag(v,k)is a square matrix of orderN+abs(k)

diag([])returns an empty matrix,[]

Data Types:single|double|int8|INT16|INT32|int64|uint8|UINT16|uint32|uint64|logical|char
Complex Number Support:Yes

Input matrix.diag如果返回错误,如果ndims(A) > 2

diag([])returns an empty matrix,[]

Data Types:single|double|int8|INT16|INT32|int64|uint8|UINT16|uint32|uint64|logical|char
Complex Number Support:Yes

Diagonal number, specified as an integer.k=0represents the main diagonal,K> 0is above the main diagonal, andk<0is below the main diagonal.

For anm-经过-nmatrix,k在范围内 ( m + 1 ) k ( n 1 ) 。例如,对于与ngreater thanm, thek=0main diagonal consists of the elements with indices(1,1),(2,2), ...,(m,m)。这k=1above the main diagonal consists of the elements with indices(1,2),(2,3), ...,(m,m+1)。这k=-1在主角下方由带有指数的元素组成(2,1),(3,2), ...,(M,M-1)

Diagonal numbers k=0, k>0, and k<0

提示

  • 痕迹矩阵等于sum(diag(A))

Extended Capabilities

Version History

在R2006a之前引入