NumPy ones() function

In this tutorial, we will cover numpy.matlib.ones() function of the Numpy library.

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:



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    

[[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))  

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

matrix([[1., 1., 1., 1., 1.]])


In this tutorial we learned about numpy.ones() mathematical function in the Numpy library. We also covered its syntax, parameters as well as the value returned by this function along with few code examples.