Open In App

randn() function - NumPy

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

The numpy.matlib.randn() function in NumPy is used to generate random matrices. It draws values from a standard normal distribution with mean 0 and variance 1. This is especially useful for creating random data for testing and simulations.

Below example that generates a 2x2 random matrix.

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

Output
[[-1.40129844 -0.87995395]
 [-0.59304405 -0.19914659]]

Explanation: This creates a 2x2 matrix with random values drawn from the standard normal distribution.

Syntax

numpy.matlib.randn(*args)
  • Parameters: *args - Shape of the output matrix (integers or a tuple).
  • Return Value: Returns a random matrix with the given shape, values drawn from the standard normal distribution.

Examples

Example 1: In this example, we generate a row vector (1x5 matrix).

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

Output
[[ 1.03493882 -0.23688495 -0.22373289  0.34506355 -1.62164563]]

Example 2: In this example, more than one argument is passed and NumPy generates the matrix accordingly.

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

Output
[[ 0.72797645  0.05098546 -0.83234051]
 [-1.74050511  0.60439976 -0.61256116]
 [-0.79913389  0.57650142 -0.08872471]
 [ 1.24549462  0.32149173  0.81629712]
 [ 0.74329914 -1.00037146 -1.73600625]]

Explanation: Here, first argument (5,3) defines the shape and second argument 4 is ignored. Only the first tuple argument is considered.

Example 3: In this example, we generate a matrix with values from a normal distribution with mean 3 and standard deviation 2.

Python
import numpy as np
import numpy.matlib
mat = 2 * np.matlib.randn(3, 3) + 3
print(mat)

Output
[[ 2.63653516  0.53801754  1.17367245]
 [ 4.03588268  5.32839196  3.15122195]
 [ 5.06144531  3.88976957 -0.35664423]]

Explanation: Multiplying by σ (2) scales the spread and adding μ (3) shifts the mean. Thus, values are sampled from N(3, 4).


Explore