In this article, we will cover generating a Vandermonde matrix of a given degree in Python using NumPy. In algebra, a Vandermonde matrix is an m*n matrix that has the terms of a geometric progression in each row.
The matrix generated will be of the form :
[1 x11 x12 ........ x1(n-1) ................... ................... 1 xm1 xm2 ........ xm(n-1)]
numpy.polynomial.polynomial.polyvander
The numpy.polynomial.polynomial.polyvander() method is used to generate a Vandermonde matrix of a given array using the NumPy module in Python. This method accepts an array and matrix’s degree that specifies the degree of the matrix. It returns a matrix containing the Vandermonde matrix. The syntax of the polyvander method is given as:
Syntax: numpy.polynomial.polynomial.polyvander():
Parameters:
- x: array like object.
- deg: integer. The resulting matrix’s degree.
Returns: The Vandermonde matrix.
Example 1:
Here, we will create a NumPy array and use numpy.polynomial.polynomial.polyvander() to generate a vandermonde matrix. The shape of the array is found by the .shape attribute, the dimension of the array is found by .ndim attribute, and the data type of the array is .dtype attribute.
Python3
# import packages import numpy as np from numpy.polynomial.polynomial import polyvander # Creating an array array = np.array([[ 4 , 3 , 1 ]]) print (array) # shape of the array is print ( "Shape of the array is : " , array.shape) # dimension of the array print ( "The dimension of the array is : " , array.ndim) # Datatype of the array print ( "Datatype of our Array is : " , array.dtype) # generating vandermonde matrix of # given degree print (polyvander(array, 2 )) |
Output:
[[4 3 1]] Shape of the array is : (1, 3) The dimension of the array is : 2 Datatype of our Array is : int64 [[[ 1. 4. 16.] [ 1. 3. 9.] [ 1. 1. 1.]]]
Example 2:
Here, the output of the second column in the matrix is negative numbers as the odd power of a negative number is always negative.
Python3
# import packages import numpy as np from numpy.polynomial.polynomial import polyvander # Creating an array array = np.array([[ - 1 , - 2 , - 3 ]]) print (array) # shape of the array is print ( "Shape of the array is : " ,array.shape) # dimension of the array print ( "The dimension of the array is : " ,array.ndim) # Datatype of the array print ( "Datatype of our Array is : " ,array.dtype) # generating vandermonde matrix of # given degree print (polyvander(array, 2 )) |
Output:
[[-1 -2 -3]] Shape of the array is : (1, 3) The dimension of the array is : 2 Datatype of our Array is : int64 [[[ 1. -1. 1.] [ 1. -2. 4.] [ 1. -3. 9.]]]