Skip to main content









How to Visualize Hilbert Matrix in Python Using Matplotlib (2D & 3D Examples)

How to Visualize Hilbert Matrix in Python Using Matplotlib (2D & 3D Examples)

By Pawel Jastrzebski

The Hilbert matrix is a classic example used in numerical analysis and linear algebra. Originally demonstrated using MATLAB, here we reproduce and expand the visualization using Python and Matplotlib. This guide covers everything from defining the Hilbert matrix, generating values using for loops and vectorized Python functions, to creating 2D heatmaps and 3D surface plots with colorbars for enhanced clarity.

What Is a Hilbert Matrix?

The Hilbert matrix is a square matrix with elements defined by the formula:

H[i][j] = 1 / (i + j - 1)

It is symmetric and positive definite, with elements that quickly approach zero as they move away from the diagonal.

Python Imports and Settings

Before generating our matrix and visualizations, import necessary libraries and configure NumPy display settings.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

np.set_printoptions(formatter={'float': '{: 0.2f}'.format})

Creating the Hilbert Matrix

Method 1: Using For Loops

This is the most verbose and computationally expensive method, suitable for educational purposes or small matrices.

def hilbert_matrix_loops(n):
    H = np.zeros((n, n))
    for i in range(n):
        for j in range(n):
            H[i, j] = 1 / (i + j + 1)
    return H

Method 2: Using Vectorization

Numpy’s broadcasting makes it easy to construct the matrix using vectorized operations for better performance.

def hilbert_matrix_vectorized(n):
    i = np.arange(n).reshape((n, 1))
    j = np.arange(n).reshape((1, n))
    return 1 / (i + j + 1)

Wrap in a Function

Encapsulate the logic for reuse and flexibility.

def generate_hilbert_matrix(n, method='vectorized'):
    if method == 'loops':
        return hilbert_matrix_loops(n)
    elif method == 'vectorized':
        return hilbert_matrix_vectorized(n)
    else:
        raise ValueError("Invalid method. Use 'loops' or 'vectorized'.")

2D Visualization: Heatmap

Use Matplotlib’s imshow and colorbar to render the Hilbert matrix as a 2D heatmap.

def plot_heatmap(hilbert):
    plt.imshow(hilbert, cmap='viridis')
    plt.title("Hilbert Matrix Heatmap")
    plt.colorbar(label='Value')
    plt.show()

Example usage:

H = generate_hilbert_matrix(10)
plot_heatmap(H)

3D Visualization: Surface Plot

Create a 3D surface plot using mpl_toolkits.mplot3d to visualize curvature and depth.

def plot_surface(hilbert):
    n = hilbert.shape[0]
    x = np.arange(n)
    y = np.arange(n)
    X, Y = np.meshgrid(x, y)
    Z = hilbert

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    surf = ax.plot_surface(X, Y, Z, cmap='viridis')
    fig.colorbar(surf, ax=ax, shrink=0.5, aspect=5)
    ax.set_title("Hilbert Matrix Surface Plot")
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')
    ax.set_zlabel('Value')
    plt.show()

Example usage:

H = generate_hilbert_matrix(10)
plot_surface(H)

Applications of the Hilbert Matrix

Hilbert matrices are often used as test problems in numerical analysis for methods dealing with poorly conditioned matrices. These matrices are useful for practicing linear algebra concepts including:

  • Matrix inversion
  • Determinant calculation
  • Solving linear equations
  • Eigenvalue and singular value computations

Conclusion

Visualizing Hilbert matrices in Python is a great way to explore numerical precision, matrix operations, and data visualization techniques. With simple tools like Numpy and Matplotlib, both 2D and 3D representations can be created effectively.

Try experimenting with larger matrix sizes, different colormaps, or even animations to further explore how visualization can aid in understanding linear algebra concepts.

© 2024 by Pawel Jastrzebski. All rights reserved.


Leave a Reply

Close Menu

Wow look at this!

This is an optional, highly
customizable off canvas area.

About Salient

The Castle
Unit 345
2500 Castle Dr
Manhattan, NY

T: +216 (0)40 3629 4753
E: hello@themenectar.com