Signup/Sign In
LAST UPDATED: DECEMBER 12, 2020

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:

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


[[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
np.matlib.ones(5)


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

Summary

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.



About the author:
Aspiring Software developer working as a content writer. I like computer related subjects like Computer Networks, Operating system, CAO, Database, and I am also learning Python.