diagCreating diagonal matrix, or extracting diagonal elements
diag(A)A is a vector, it returns a matrix whose diagonal elements are given by A. The off-diagonal elements are all zeros.A is a matrix, it returns a row vector containing the diagonal elements of A.A is a scalar, it returns A.A is empty, it returns an empty array.ndim(A) == 2 must hold.X = diag(A, k)k should be a real integer scalar not equal to Inf nor NaN.
If k is zero, it gives the same result as diag(A).
When A is a vector and
k > 0, it returns a matrix whose k-th upper diagonal elements are given by A. The other elements are all zeros.k < 0, it returns a matrix whose k-th lower diagonal elements are given by A. The other elements are all zeros.When A is a matrix and
k > 0, it returns the k-th upper diagonal. If k is larger than or equal to the width of A, it returns an empty array.k < 0, it returns the k-th lower diagonal. If abs(k) is larger than or equal to the height of A, it returns an empty array. A cannot have more than 2 dimensions.
v = [10 20 30];
X = diag(v,3)
X =
0.000 0.000 0.000 10.00 0.000 0.000
0.000 0.000 0.000 0.000 20.00 0.000
0.000 0.000 0.000 0.000 0.000 30.00
0.000 0.000 0.000 0.000 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000
v = [10 20 30];
X = diag(v,-3)
X =
0.000 0.000 0.000 0.000 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000
10.00 0.000 0.000 0.000 0.000 0.000
0.000 20.00 0.000 0.000 0.000 0.000
0.000 0.000 30.00 0.000 0.000 0.000
A = randi(10,5,5)
diag(A, 3)
A =
6.000 5.000 4.000 5.000 7.000
1.000 1.000 6.000 1.000 8.000
7.000 9.000 5.000 2.000 10.00
5.000 9.000 8.000 1.000 10.00
5.000 5.000 5.000 5.000 3.000
ans =
5.000 8.000
A = randi(10,5,5)
diag(A, -3)
A =
10.00 10.00 2.000 6.000 8.000
6.000 9.000 7.000 3.000 5.000
9.000 9.000 4.000 1.000 4.000
3.000 2.000 7.000 2.000 6.000
1.000 4.000 8.000 8.000 6.000
ans =
3.000 4.000