Creating a diagonal matrix in Matlab

The diag() function in Matlab offers a straightforward way to create a diagonal matrix.

diag(v, k)

  • The first parameter, v, is an array or vector containing the values to place along the matrix's diagonal.
  • The second parameter, k, is an integer that indicates the diagonal’s position relative to the main diagonal. By default, k = 0 targets the main diagonal.

For example, let’s begin by creating an array with the elements 1, 4, and 2:

an array with 3 elements

Next, I use the diag(v) function to generate a diagonal matrix, placing the elements 1, 4, and 2 along the main diagonal:

the diagonal matrix

To shift the diagonal above the main one, I can set the k parameter to a positive integer (e.g., 1, 2, 3, ...):

example of diagonal matrix with upper offset

Alternatively, using a negative value for k (such as -1, -2, -3) moves the diagonal below the main one:

example of diagonal matrix with lower offset

For instance, k = -1 refers to the diagonal just below the main diagonal.

 
 

Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

FacebookTwitterLinkedinLinkedin
knowledge base

Matrix in Matlab