Generate a Vandermonde matrix of given degree in Python

To generate a Vandermonde matrix of given degree, use the polynomial.polyvander() function in Python NumPy. The method returns the Vandermonde matrix where each row represents the powers of the corresponding input value. The shape of the returned matrix is x.shape + (deg + 1,), where the last index is the power of x.

Syntax

numpy.polynomial.polynomial.polyvander(x, deg)

Parameters

The function accepts the following parameters ?

  • x ? Array of points. The dtype is converted to float64 or complex128 depending on whether any elements are complex. If x is scalar, it is converted to a 1-D array.
  • deg ? The degree of the resulting matrix (non-negative integer).

Example

Let's create a Vandermonde matrix of degree 2 ?

import numpy as np
from numpy.polynomial.polynomial import polyvander

# Create an array
x = np.array([0, 1, -1, 2])

# Display the array
print("Our Array...")
print(x)

# Check the dimensions
print("\nDimensions of our Array...")
print(x.ndim)

# Get the datatype
print("\nDatatype of our Array object...")
print(x.dtype)

# Get the shape
print("\nShape of our Array object...")
print(x.shape)

# Generate a Vandermonde matrix of degree 2
result = polyvander(x, 2)
print("\nVandermonde matrix (degree 2)...")
print(result)
Our Array...
[ 0  1 -1  2]

Dimensions of our Array...
1

Datatype of our Array object...
int64

Shape of our Array object...
(4,)

Vandermonde matrix (degree 2)...
[[ 1.  0.  0.]
 [ 1.  1.  1.]
 [ 1. -1.  1.]
 [ 1.  2.  4.]]

Understanding the Matrix

Each row in the Vandermonde matrix contains powers of the corresponding input value from 0 to the specified degree ?

import numpy as np
from numpy.polynomial.polynomial import polyvander

# Example with different degree
x = np.array([1, 2, 3])
matrix = polyvander(x, 3)

print("Input array:", x)
print("\nVandermonde matrix (degree 3):")
print(matrix)

print("\nExplanation:")
for i, val in enumerate(x):
    print(f"Row {i}: [{val}^0, {val}^1, {val}^2, {val}^3] = {matrix[i]}")
Input array: [1 2 3]

Vandermonde matrix (degree 3):
[[ 1.  1.  1.  1.]
 [ 1.  2.  4.  8.]
 [ 1.  3.  9. 27.]]

Explanation:
Row 0: [1^0, 1^1, 1^2, 1^3] = [1. 1. 1. 1.]
Row 1: [2^0, 2^1, 2^2, 2^3] = [1. 2. 4. 8.]
Row 2: [3^0, 3^1, 3^2, 3^3] = [ 1.  3.  9. 27.]

Conclusion

The polyvander() function efficiently generates Vandermonde matrices for polynomial fitting and interpolation. Each row contains consecutive powers of the input values from 0 to the specified degree.

Updated on: 2026-03-26T19:39:02+05:30

674 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements