NumPy ones() function

The function numpy.matlib.ones() is used to return the matrix of given shape and type. This function initializes all the values of the matrix to one(1).

The numpy.matlib is a matrix library used to configure matrices instead of ndarray objects.

Syntax of matlib.ones():

The required syntax to use this function is as follows:

numpy.matlib.ones(shape,dtype,order)

Parameters:

Let us now cover the parameters used with this function:

  • shape
    This parameter is in the form of a tuple that is used to define the shape of the matrix.
  • dtype
    This parameter is used to indicate the data type of the matrix. The default value of this parameter is float. This is an optional parameter.
  • order
    This is an optional parameter that is used to indicate the insertion order of the matrix. It mainly indicates whether to store the result in C- or Fortran-contiguous order, The default value is ‘C’.

Returned Values:

This function will return a matrix with all the entries initialized to 1.

Now it’s time to cover a few examples of this function.

Example 1:

Given below is a basic example for the understanding of this function:

import numpy as np    
import numpy.matlib    
    
print(numpy.matlib.ones((5,4)))    

Output:


[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]

Example 2:

Now we will also use type and order parameter in the code snippet given below:

import numpy as np    
import numpy.matlib    
    
print("The Output matrix is :\n",numpy.matlib.ones((3,4),int))  

Output:


The Output matrix is :
[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]

Example 3:

One more example,

import numpy as np

# 1-d array with 5 elements
np.matlib.ones(5)

Output:


matrix([[1., 1., 1., 1., 1.]])
Follow Us On