Arrays based on existing arrays

Some of the NumPy array-creation routines are extremely useful to perform matrix operations such as constructing the diagonal matrix (diag), the upper triangular matrix (triu), and the lower triangular matrix (tril).

The diag function works only on 1D and 2D arrays. If the input array is 2D, the output is a 1D array with the diagonal elements of the input array. If the input is a 1D array, the output is a matrix with the input array along its diagonal. Here, a parameter k helps to offset the position from the main diagonal and can be positive or negative:

# The 2D input matrix for diag function
In [68]: arr_a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
In [69]: arr_a
Out [69]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

# Getting the diagonal of the array
In [70]: np.diag(arr_a)
Out [70]: array([1, 5, 9])

# Constructing the diagonal matrix from a 1D array
# diag returns a 1D array of diagonals for a 2D input matrix. This 1D array of diagonals can be used here.
In [71]: np.diag(np.diag(arr_a))
Out [71]:
array([[1, 0, 0],
[0, 5, 0],
[0, 0, 9]])

# Creating the diagonal matrix with diagonals other than main diagonal
In [72]: np.diag(np.diag(arr_a, k = 1))
Out [72]:
array([[2, 0],
[0, 6]])

The triu and tril functions have a similar parameter k, which helps offset the diagonal. These functions work with any ndarray.

Given an array of n dimensions, a new array can be created by repeating this array multiple times along each axis. This can be done with the tile function. This function accepts two input arguments—the input array and the number of repetitions:

# Repeating a 1D array 2 times
In [76]: np.tile(np.array([1, 2, 3]), 2)
Out [76]: array([1, 2, 3, 1, 2, 3])

# Repeating a 2D array 4 times
In [77]: np.tile(np.array([[1, 2, 3], [4, 5, 6]]), 4)
Out [77]:
array([[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3],
[4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]])

# Repeating a 2D array 4 times along axis 0 and 1 time along axis 1
In [78]: np.tile(np.array([[1, 2, 3], [4, 5, 6]]), (4,1))
Out [78]:
array([[1, 2, 3],
[4, 5, 6],
[1, 2, 3],
[4, 5, 6],
[1, 2, 3],
[4, 5, 6],
[1, 2, 3],
[4, 5, 6]])
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset