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.
 - k
 - The dimension to either place the diagonal vector, or to take the diagonal vector from.
 - m,n
 - Dimensions of the resulting matrix.
 
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