diag

Creates a diagonal matrix or returns the diagonal elements of a matrix on diagonal k.

Syntax

R = diag(v)

R = diag(v,k)

R = diag(v,m,n)

R = diag(M)

R = diag(M,k)

Inputs

v
The diagonal vector to make a diagonal matrix from.
Any valid scalar | vector | matrix
Type: double | integer | logical | struct | cell
Dimension: scalar | vector | matrix
k
The dimension to either place the diagonal vector, or to take the diagonal vector from.
Diagonal.
Type: double | integer
Dimension: scalar
m,n
Dimensions of the resulting matrix.
Type: double | integer
Dimension: scalar

Outputs

R
Either the returned diagonal matrix or diagonal vector.

Examples

Simple diag example:

diag([1,2,3])
ans = [Matrix] 3 x 3
1  0  0
0  2  0
0  0  3

Specifying the dimension to put the diagonal on:

diag([1,2,3],2)
ans = [Matrix] 5 x 5 Rows[1:3] Columns[1:5]
0  0  1  0  0
0  0  0  2  0
0  0  0  0  3
0  0  0  0  0
0  0  0  0  0

Specifying the dimension of the returned matrix:

diag([1 2 3],3,4)
ans = [Matrix] 3 x 4
1  0  0  0
0  2  0  0
0  0  3  0

Inputting a matrix returns the diagonal of the matrix:

diag([1 0 0; 0 2 0; 0 0 3])
ans = [Matrix] 3 x 1
1
2
3

Inputting a matrix, specifying the dimension of the desired diagonal:

diag([1 3 5; 2 4 8; 6 7 9],1)
ans = [Matrix] 2 x 1
3
8