Issue
I am trying to plot a constant function in python (this is not what I am actually trying to do but if I solve this it might be a first step).
import matplotlib.pyplot as plt
import numpy as np
def constant_function(x):
return 2
t1 = np.arange(0.0,1.0,0.1)
plt.plot(t1,constant_function(t1))
However I get the error
ValueError: x and y must have same first dimension, but have shapes (10,) and (1,)
Solution
One option is to vectorize
your function:
import matplotlib.pyplot as plt
import numpy as np
@np.vectorize
def constant_function(x):
return 2
t1 = np.arange(0.0, 1.0, 0.1)
plt.plot(t1, constant_function(t1))
plt.show()
this way constant_function(t1)
will return [2 2 2 2 2 2 2 2 2 2]
(i.e. [f(x[0]), f(x[1]), f(x[2]), ...]
) instead of just 2
and the dimensions will match.
Answered By - hiro protagonist
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.