Create diagonal matrix or get diagonals from symbolic matrices
D = diag(v)
D = diag(v,k)
x = diag(A)
x = diag(A,k)
example
D = diag(v) returns a square diagonal matrix with vector v as the main diagonal.
v
D = diag(v,k) places vector v on the kth diagonal. k = 0 represents the main diagonal, k > 0 is above the main diagonal, and k < 0 is below the main diagonal.
k
k = 0
k > 0
k < 0
x = diag(A) returns the main diagonal of A.
A
x = diag(A,k) returns the kth diagonal of A.
collapse all
Create a symbolic matrix with the main diagonal specified by the vector v.
syms a b c v = [a b c]; diag(v)
ans = [ a, 0, 0] [ 0, b, 0] [ 0, 0, c]
Create a symbolic matrix with the second diagonal below the main diagonal specified by the vector v.
syms a b c v = [a b c]; diag(v,-2)
ans = [ 0, 0, 0, 0, 0] [ 0, 0, 0, 0, 0] [ a, 0, 0, 0, 0] [ 0, b, 0, 0, 0] [ 0, 0, c, 0, 0]
Extract the main diagonal from a square matrix.
syms x y z A = magic(3).*[x, y, z]; diag(A)
ans = 8*x 5*y 2*z
Extract the first diagonal above the main diagonal.
syms x y z A = magic(3).*[x, y, z]; diag(A,1)
ans = y 7*z
Diagonal elements, specified as a symbolic vector. If v is a vector with N elements, then diag(v,k) is a square matrix of order N + abs(k).
N
diag(v,k)
N + abs(k)
Input matrix, specified as a symbolic matrix.
Diagonal number, specified as an integer. k = 0 represents the main diagonal, k > 0 is above the main diagonal, and k < 0 is below the main diagonal.
The trace of a matrix is equal to sum(diag(A)).
trace
sum(diag(A))
tril | triu
tril
triu