Array of ones and zeros

Several operations on arrays call for the creation of arrays or matrices with ones and zeros. Some special functions in NumPy provide for easy creation of such arrays. Usually, these functions take in the shape of the resultant array as an input argument in the form of a tuple:

# Creating an array of ones with shape (2, 3, 4)
In [27]: np.ones((2, 3, 4))
Out [27]:
array([[[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]],
[[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]]])

# Creating an array of zeros with shape (2, 1, 3)
In [28]: np.zeros((2, 1, 3))
Out [28]:
array([[[0., 0., 0.]],
[[0., 0., 0.]]])

The identity function returns a 2D n x n square matrix, where n is the order of the matrix passed as an input argument:

In [29]: np.identity(3)
Out [29]:
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])

The eye function can also be used to create an identity matrix. It differs from the identity matrix in two main aspects:

  • The eye function returns a 2D rectangular matrix and accepts both the number of rows and number of columns (optional argument) as the input. If the number of columns is not specified, a square matrix is returned using just the number of rows passed in.
  • The diagonal can be offset to any position in the upper triangle or lower triangle.

Take a look at the following code:

# Creating an identity matrix of order 3 with the eye function
In [39]: np.eye(N = 3)
Out [39]:
array([[1., 0., 0.],
[0., 1., 0.],[0., 0., 1.]])

# Creating a rectangular equivalent of identity matrix with 2 rows and 3 columns
In [40]: np.eye(N = 2, M = 3)
Out [40]:
array([[1., 0., 0.],
[0., 1., 0.]])

# Offsetting the diagonal of ones by one position in the upper triangle
In [41]: np.eye(N = 4, M = 3, k = 1)
Out [41]:
array([[0., 1., 0.],
[0., 0., 1.],
[0., 0., 0.],
[0., 0., 0.]])

# Offsetting the diagonal of ones by two positions in the lower triangle
In [42]: np.eye(N = 4, M = 3, k = -2)
Out [42]:
array([[0., 0., 0.],
[0., 0., 0.],
[1., 0., 0.],
[0., 1., 0.]])

By default, k holds the value 0 in the eye function.

..................Content has been hidden....................

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