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 asnpfrom numpy.linalg import jacobian: imports thejacobianfunction from thenumpy.linalgmoduledef 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 do I create a zero matrix using Python and Numpy?
- How do I use Scipy zeros in Python?
- How can I use Python Scipy to zoom in on an image?
- How can I use Python and Numpy to parse XML data?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How do I use Python Scipy to generate a PDF?
- How do I use Python and SciPy to create a tutorial PDF?
- How can I use Python and Numpy to zip files?
- How do I calculate the cross-correlation of two arrays using Python and NumPy?
See more codes...