NumPy Tutorial NumPy Statistics NumPy References

NumPy - matlib.ones() function



The NumPy matlib.ones() function returns a matrix of given shape and type, filled with ones.

Syntax

numpy.matlib.ones(shape, dtype=None, order='C')

Parameters

shape Required. Specify shape of the matrix.
dtype Optional. Specify the desired data-type for the matrix. Default: float
order Optional. Specify whether to store the result. Two possible values are: C (C-style) and F (Fortran-style). Default: 'C'

Return Value

Returns a matrix of ones with the given shape, dtype, and order.

Example: Create a matrix of ones

In the example below, matlib.ones() function is used to create a matrix of ones of specified shape.

import numpy as np
import numpy.matlib

mat = np.matlib.ones((2,3))
print(mat)

The output of the above code will be:

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

Example: matlib.ones() with scalar or length one

If shape has length one i.e. (N,), or is a scalar N, the returned matrix will be a single row matrix of shape (1,N). Consider the following example.

import numpy as np
import numpy.matlib

mat1 = np.matlib.ones(2)
print("mat1 is:", mat1)

mat2 = np.matlib.ones((3,))
print("mat2 is:", mat2)

The output of the above code will be:

mat1 is: [[1. 1.]]
mat2 is: [[1. 1. 1.]]

Example: matlib.ones() function with dtype parameter

The matlib.ones() function can be used with dtype parameter to provide the data type of the elements of the matrix. In the example below, data type of the matrix is complex.

import numpy as np
import numpy.matlib

mat = np.matlib.ones((2,2), dtype=complex)
print(mat)

The output of the above code will be:

[[1.+0.j 1.+0.j]
 [1.+0.j 1.+0.j]]

❮ NumPy - Functions