Unlocking the Power of Diagonal Arrays

Creating Diagonal Arrays

The diag() method is a powerful tool for working with arrays, allowing you to create or extract diagonal elements from arrays. One of its primary uses is creating a new array with diagonal elements from a 1D array.

The diag() method takes an optional k argument, which controls the placement of the diagonal elements. By default, k is set to 0, representing the main diagonal. You can set k to a positive integer to create diagonals above the main diagonal, or a negative integer to create diagonals below it.

Let’s see this in action:

import numpy as np

input_array = [1, 2, 3, 4]
diagonal_array = np.diag(input_array)

print(diagonal_array)

Output:

[
 [1, 0, 0, 0],
 [0, 2, 0, 0],
 [0, 0, 3, 0],
 [0, 0, 0, 4]
]

Extracting Diagonals from 2D Arrays

The diag() method is also useful for extracting diagonal elements from 2D arrays. When you pass a 2D array to diag(), it returns a 1D array containing the diagonal elements of the original array.

Let’s take a look at an example:

import numpy as np

input_array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
diagonal_elements = np.diag(input_array)

print(diagonal_elements)

Output:

[1, 5, 9]

Related Methods: diagflat()

Did you know that there’s a related method called diagflat()? This method creates a 2D array with the flattened input as its diagonal. The key difference is that diagflat() automatically flattens the input array, whereas diag() requires manual flattening using the flatten() method.

import numpy as np

input_array = [1, 2, 3, 4]
diagonal_array = np.diagflat(input_array)

print(diagonal_array)

Output:

[
 [1, 0, 0, 0],
 [0, 2, 0, 0],
 [0, 0, 3, 0],
 [0, 0, 0, 4]
]

By mastering the diag() method and its related cousins, you’ll be able to unlock new possibilities in your array manipulation workflows.

Leave a Reply