NumPy – Using matlib.randn() function (4 examples)

Updated: February 27, 2024 By: Guest Contributor Post a comment

Introduction

NumPy is an essential library in the Python data science ecosystem, offering comprehensive support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays. An interesting part of NumPy is the matlib module, which provides matricial operations. The randn() function within this module is particularly useful for generating random matrices from a standard normal distribution. This tutorial explores the randn() function through five progressive examples, demonstrating its versatility and use cases in data analysis and scientific computing.

What is matlib.randn()?

The randn() function generates a matrix filled with random floats sampled from a univariate “normal” (Gaussian) distribution of mean 0 and variance 1. It’s crucial for stochastic simulation, statistical modeling, and many other applications requiring random data generation.

The syntax for numpy.random.randn() is as follows:

numpy.random.randn(d0, d1, ..., dn)

Where d0, d1, …, dn are the dimensions of the output array. They are optional and represent the shape of the output array. If no arguments are provided, a single random number is generated.

Example 1: Basic Usage

import numpy as np
import numpy.matlib

# Generating a 2x3 random matrix
matrix1 = np.matlib.randn(2, 3)
print(matrix1)

This example demonstrates the basic usage of randn() to generate a 2×3 matrix. Each time you execute this code, the matrix will contain different random numbers, showcasing the stochastic nature of this function.

A possible output:

[[-1.24828595  0.19141674  0.52857805]
 [ 2.0610369   0.44054487 -0.31444213]]

Example 2: Generating square matrices

import numpy as np
import numpy.matlib

# Generating a 3x3 random matrix
matrix2 = np.matlib.randn(3, 3)
print(matrix2)

By specifying the same number for both dimensions, you can easily create square random matrices, which are particularly useful for certain linear algebra applications and simulations.

A possible output:

[[-0.9093334   0.23402819  0.46599554]
 [-0.28165805 -0.20994865 -0.13897204]
 [ 0.73955399 -1.10373281 -1.12103177]]

Example 3: Using randn() with variable dimensions

import numpy as np
import numpy.matlib

# Define dimensions dynamically
rows = 4
cols = 5

# Generating dynamically sized matrix
matrix4 = np.matlib.randn(rows, cols)
print(matrix4)

In this more advanced example, we see that the dimensions of the matrix generated by randn() can be set dynamically, utilizing variables. This is especially useful in scenarios where the size of the data structure cannot be predetermined, such as in certain simulations or when dealing with user-generated input.

A possible output:

[[-0.2457797  -0.24117333  1.02233279 -0.36966753 -0.5583422 ]
 [ 1.0334123   0.00353288  0.59519579 -0.81449582 -1.58642108]
 [ 0.64544251 -1.63992314  0.42089276 -0.86937025 -1.50917319]
 [ 1.42358041 -0.17354087  0.21760542 -0.56192085  1.74655743]]

Example 4: Seed setting for reproducibility

import numpy as np
import numpy.matlib

# Setting a random seed for reproducibility
np.random.seed(42)

# Generating a predictable 3x3 matrix
predicted_matrix = np.matlib.randn(3, 3)
print(predicted_matrix)

Output (vary due to the randomness):

[[ 0.49671415 -0.1382643   0.64768854]
 [ 1.52302986 -0.23415337 -0.23413696]
 [ 1.57921282  0.76743473 -0.46947439]]

Reproducibility is a cornerstone of scientific computing. By setting a random seed, you ensure that the randn() function generates the same random matrix across different runs, which is vital for experiments that need to be verified or shared with others. This feature is exemplary of how seemingly chaotic systems can indeed be tightly controlled and predicted within computational environments.

Example 5: Using matlib.randn() with Complex Numbers

import numpy as np
import numpy.matlib

np.random.seed(2024)

# Define dimensions of the matrix
rows, cols = 5, 5

# Generate a random matrix with complex numbers
complex_matrix = np.matlib.randn(rows, cols) + 1j * np.matlib.randn(rows, cols)

# Display the result
print("Complex-valued matrix:")
print(complex_matrix)

Output:

Complex-valued matrix:
[[ 1.66804732-0.88323043j  0.73734773-0.36618388j -0.20153776-1.53470503j
  -0.15091195-0.35157551j  0.91605181+0.63991811j]
 [ 1.16032964+0.68923917j -2.619962  +0.75725237j -1.32529457-1.43054977j
   0.45998862-0.4288793j   0.10205165-0.68501186j]
 [ 1.05355278-0.12564086j  1.62404261+1.14458724j -1.50063502+0.32720979j
  -0.27783169-0.13672744j  1.19399502+0.17919391j]
 [ 0.86181533+0.96897707j -0.41704604+0.00587009j -0.24953642+0.59050544j
   0.94367735-0.39247637j -0.76631064+0.03591147j]
 [ 0.20822873-0.33075495j  1.40872293+0.80877607j -1.48910401+0.05331094j
  -1.47580853-1.31890201j  0.99084632-1.0797807j ]]

In this example:

  • We specify the dimensions of the matrix (5 rows and 5 columns).
  • We use np.matlib.randn() to generate a random matrix with the specified dimensions. Since np.matlib.randn() only generates real-valued numbers, we add a complex component by multiplying the result with 1j * np.matlib.randn(), which generates random numbers with an imaginary part.
  • The resulting complex_matrix is a 2D array with complex-valued elements.

Conclusion

Throughout this tutorial, we explored the functionality and applications of the matlib.randn() function in NumPy, from generating basic random matrices to dealing with more complex, high-dimensional data structures. The examples illustrated how randn() can be used in various scenarios, highlighting its importance in the fields of data science, machine learning, and scientific computing. Whether for simulation, modeling, or any application requiring normal-distributed random data, matlib.randn() proves to be an invaluable tool in any data scientist’s arsenal.