I have the following function to plot:
f(x) = 3 + (x - (2 6)T )T · (x - (2 6)T)
where (2 6)
is a vector, T
represents transpose and x
is a vector of size 2. My question is how can I implement a np.linspace
so that I can get a continuous 2D function?
I have written my function in the following form:
def f(x):
a = np.array([[2],[6]])
t = lambda x: 3 + np.dot((x - (a)).T, (x - a))
return t(x)
x = np.array([[4],[1]]) # Some random (2,1) sized vector
y = f(x) # Returns an array sized (1,1)
For example, to plot a variation of the function f(x) = x^2 (x-squared)
I can write the following code:
def f(x):
return x**2
x = np.linspace(-5, 5, 20)
y = f(x)
plt.plot(x, y)
I want to know whether it is possible to plot a continuous function for a case where x
input is two-dimensional vector. If it is not feasible, how the first function should be plotted? A 3-D plot is not possible since my function only has x
as its parameter.
Edit
:
Dimension of your vectors is 2. You also have value of function for this vector. In total you have 3 parametrs, so I think it can't be plotted as 2D plot and you need to use 3D plot.(Your x
vector is just a tuple, so you can use x[0] and x[1] as axis)
@deeenizka is right that we have to plot 3 dimensions. One way to do it is to use a contour line plot.
First we have to vectorize your function to compute the values of the function with an array of 2D vectors
import numpy as np
import matplotlib.pyplot as plt
def f(x):
a = np.array([[2],[6]])
x = x - a
return 3 + np.einsum('ij,ij->j',x ,x)
To get the input coordinate vectors we can use meshgrid
and ravel
the 2D arrays to pass them to the function f
x = np.linspace(-50, 50, 100)
y = np.linspace(-50, 50, 100)
X,Y = np.meshgrid(x, y)
data = np.vstack([X.ravel(), Y.ravel()])
We can plot the data with contourf
after we reshaped the returned array of function values.
plt.figure(figsize=(8,6))
plt.contourf(X, Y, f(data).reshape(X.shape), levels=20)
plt.colorbar();
Out:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.