Array having 1 on border and 0 inside

NumPy makes it possible to create an array having 1 as border values and 0 inside. To develop this specific kind of array, many ways are available. first, let me show you, how this array looks like and then we look how to develop it.

[[1. 1. 1. 1. 1.],
 [1. 0. 0. 0. 1.],
 [1. 0. 0. 0. 1.],
 [1. 1. 1. 1. 1.]]

1. By "zeros()" function and "Slicing":

  • In NumPy, zeros() function takes one required argument n (shape) , which can be a tuple representing the dimensions of the array, or a single integer for a one-dimensional array and returns an array having all values zero’s.

  • You can use zeros() function to create a 4x4 matrix and using slicing to set its border values to 1. For example:

2. Using "pad()" function:

The "pad()" function in NumPy is used to add values to the edges of an array.

Syntax: numpy.pad(array, pad_width, mode='constant', **kwargs)

You create zeros array and then pad all border elements with 1. For example:

3. Using "meshgrid(): function:

It is used to create a coordinate grid from two or more one-dimensional arrays representing the coordinates of a set of points in a multi-dimensional space.

Syntax: X, Y = np.meshgrid(x, y, indexing='xy')

  • The meshgrid() function returns two multi-dimensional arrays X and Y that represent the coordinates of each point in the grid. The shape of X and Y will be the same, and it will be equal to the product of the lengths of the input arrays.

By using meshgrid(), we can create our required array shown below:

4. By "indices()" and "where()" function:

  • The indices() method is used to create an array of indices that can be used to index into another array. The method returns an array with the same shape as the input array, where each element of the output array contains a tuple of indices that can be used to index into the input array.
  • The where() function is a powerful tool for array manipulation in Python. It returns the indices of elements in an input array where a specified condition is true.

Following example, you can create 5x5 array having all values 1 and then we find indices and replace all elements except border elements with 0.