- Q&A
- Questions
- Unanswered
- Tags
- Users
- Ask a Question
- Articles
- Interview Questions
- Programming Quiz
- Post An Article

0 votes

In this case if you intend to employ a function that receive a single element to every element in an array, you can apply `np.vectorize. Follw the below script.`

`Code:`

```
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return np.int(x)
f2 = np.vectorize(f)
x = np.arange(1, 15.1, 0.1)
plt.plot(x, f2(x))
plt.show()
```

In some cases you can skip the definition of f(x) and only pass np.int to the vectorize function: `f2 = np.vectorize(np.int)`

.

`Remember that np.vectorize`

is only a convenience function and originally a for loop.

`x.astype(int)`

```
import numpy as np
import matplotlib.pyplot as plt
import datetime
time_start = datetime.datetime.now()
# My original answer
def f(x):
rebuilt_to_plot = []
for num in x:
rebuilt_to_plot.append(np.int(num))
return rebuilt_to_plot
for t in range(10000):
x = np.arange(1, 15.1, 0.1)
plt.plot(x, f(x))
time_end = datetime.datetime.now()
# Answer by ayhan
def f_1(x):
return np.int(x)
for t in range(10000):
f2 = np.vectorize(f_1)
x = np.arange(1, 15.1, 0.1)
plt.plot(x, f2(x))
time_end_2 = datetime.datetime.now()
print time_end - time_start
print time_end_2 - time_end
```

Hopefully, now you are able to solve this problem.