next up previous contents
Next: REPMAT Array Replication Function Up: Array Generation and Manipulations Previous: FIND Find Non-zero Elements   Contents

Subsections

DIAG Diagonal Matrix Construction/Extraction

Usage

The diag function is used to either construct a diagonal matrix from a vector, or return the diagonal elements of a matrix as a vector. The general syntax for its use is

  y = diag(x,n)

If x is a matrix, then y returns the n-th diagonal. If n is omitted, it is assumed to be zero. Conversely, if x is a vector, then y is a matrix with x set to the n-th diagonal.

Examples

Here is an example of diag being used to extract a diagonal from a matrix.

--> A = int32(10*rand(4,5))
A = 
  <int32>  - size: [4 5]
 
Columns 1 to 5
             8              6              9              9              4  
             9              0              9              4              9  
             1              2              1              8              7  
             9              5              9              1              9  
--> diag(A)
ans = 
  <int32>  - size: [4 1]
 
Columns 1 to 1
             8  
             0  
             1  
             1  
--> diag(A,1)
ans = 
  <int32>  - size: [4 1]
 
Columns 1 to 1
             6  
             9  
             8  
             9

Here is an example of the second form of diag, being used to construct a diagonal matrix.

--> x = int32(10*rand(1,3))
x = 
  <int32>  - size: [1 3]
 
Columns 1 to 3
             8              9              1  
--> diag(x)
ans = 
  <int32>  - size: [3 3]
 
Columns 1 to 3
             8              0              0  
             0              9              0  
             0              0              1  
--> diag(x,-1)
ans = 
  <int32>  - size: [4 4]
 
Columns 1 to 4
             0              0              0              0  
             8              0              0              0  
             0              9              0              0  
             0              0              1              0



Samit K. Basu 2005-03-16