D = diag(A,k) produces diagonal matrices or extracts diagonals of a matrix A.

diag(V,K) when V is a vector with n components is a square matrix of order n+ABS(k) with the elements of V on the k-th diagonal. k = 0 is the main diagonal, k > 0 is above the main diagonal and k < 0 is below the main diagonal.

diag(V) is the same as diag(V,0) and puts V on the main diagonal.

diag(X,k) when X is a matrix is a column vector formed from the elements of the k-th diagonal of X.

diag(X) is the main diagonal of X.


A is a vector or matrix of NCpolys

k is an integer


vector or matrix of NCpolys

possible usage:

diag(A), diag(A,k)


>> diag([x x^2 x*y-y*x])

ans =  x     0         0

       0   x^2         0

       0     0   x*y-y*x

>> diag([x x^2 x*y-y*x],1)

ans = 0   x     0         0

      0   0   x^2         0

      0   0     0   x*y-y*x

      0   0     0         0

>> A=[x x^2 x*y-y*x; y x*y 2*x-y]

A =  x   x^2   x*y-y*x

     y   x*y     2*x-y

>> diag(A)

ans =   x


>> diag(A,1)

ans =   x^2