python-scipyHow do I calculate a Jacobian matrix using Python and NumPy?
The Jacobian matrix is a matrix of partial derivatives of a vector-valued function with respect to its inputs. To calculate a Jacobian matrix using Python and NumPy, we can use the jacobian
function from the numpy.linalg
module. This function takes a vector-valued function as its argument and returns its Jacobian.
For example, given a vector-valued function f(x, y):
def f(x, y):
return np.array([x*y, x**2 + y**2])
We can calculate its Jacobian matrix as follows:
import numpy as np
from numpy.linalg import jacobian
def f(x, y):
return np.array([x*y, x**2 + y**2])
x, y = 2, 3
jacobian(f, (x, y))
The output of the above code is:
array([[3., 2.],
[4., 6.]])
Code explanation
import numpy as np
: imports the NumPy library asnp
from numpy.linalg import jacobian
: imports thejacobian
function from thenumpy.linalg
moduledef f(x, y):
: defines the vector-valued function f(x, y)jacobian(f, (x, y))
: calculates the Jacobian matrix of vector-valued function f(x, y)
Helpful links
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How can I use Python and SciPy to extrapolate data?
- How do I create a zero matrix using Python and Numpy?
- How do I create a numpy array of zeros using Python?
- How do I create a numpy array of zeros using Python?
- How can I use Python and SciPy to find the zeros of a function?
- How do I use the numpy vstack function in Python?
- How do I create an array of zeros with the same shape as an existing array using Python and NumPy?
- How do I use Scipy zeros in Python?
- How do I use the trapz function in Python SciPy?
See more codes...