Open In App

numpy matrix operations - rand() function

Last Updated : 27 Sep, 2025
Suggest changes
Share
Like Article
Like
Report

The function numpy.matlib.rand() is used to generate a random matrix with values drawn uniformly from range [0, 1). Unlike numpy.random.rand() which returns an ndarray, this function always returns a matrix object. It is useful when you want matrix operations instead of standard arrays.

In this example we create a 2×2 random matrix.

Python
import numpy as np
import numpy.matlib
mat = np.matlib.rand(2, 2)
print(mat)

Output
[[0.76798661 0.30463462]
 [0.91308492 0.52278504]]

Explanation: np.matlib.rand(2, 2) generates a 2×2 matrix filled with random values between 0 and 1. Each run will produce different results.

Syntax

numpy.matlib.rand(*args)
  • Parameters: *args (int or tuple) - Shape of the output matrix. If a tuple is provided, it defines the full shape; otherwise, integers specify each dimension.
  • Return Value: matrix - NumPy matrix of random values from a uniform distribution [0, 1).

Examples

Example 1: Generate a random 3×4 matrix using a tuple shape.

Python
import numpy as np
import numpy.matlib

mat = np.matlib.rand((3, 4))
print(mat)

Output
[[0.86044571 0.7866     0.86143353 0.13050542]
 [0.41484943 0.52375644 0.90333131 0.78733028]
 [0.12783183 0.86338443 0.3828335  0.23667251]]

Explanation: shape (3, 4) produces a 3×4 random matrix where each element is between 0 and 1.

Example 2: Generate a random row matrix with 5 columns.

Python
import numpy as np
import numpy.matlib
mat = np.matlib.rand(5)
print(mat)

Output
[[0.78435911 0.52598192 0.15842468 0.68187966 0.02272941]]

Explanation: Passing a single integer creates a 1×N matrix. Here, 5 generates a 1×5 random row matrix.

Example 3: Demonstrate what happens if both a tuple and another argument are provided.

Python
import numpy as np
import numpy.matlib
mat = np.matlib.rand((5, 3), 4)
print(mat)

Output
[[0.58984104 0.40018229 0.28423643]
 [0.41439193 0.11351546 0.1271194 ]
 [0.12692327 0.1397911  0.19475829]
 [0.80711764 0.40346092 0.9755756 ]
 [0.74676111 0.49863317 0.37346994]]

Explanation: Even though (5, 3) and 4 are passed, only the tuple (5, 3) is considered, producing a 5×3 matrix.


Explore