[英]How to write a vector function to apply operation f(x,y)?
scalar_function can only handle scalar input, we could use the function np.vectorize() turn it into a vectorized function.
scalar_function 只能处理标量输入,我们可以使用函数 np.vectorize() 将其转换为向量化函数。 Note that the input argument of np.vectorize() should be a scalar function, and the output of np.vectorize() is a new function that can handle vector input.
注意 np.vectorize() 的输入参数应该是一个标量函数,而 np.vectorize() 的输出是一个可以处理向量输入的新函数。
Please write a vector function vector_function, which will apply the operation 𝑓(𝑥,𝑦) defined above element-wisely with input vectors with same dimension x and y.
请编写一个向量函数vector_function,它将对具有相同维度x和y的输入向量逐元素地应用上面定义的操作𝑓(𝑥,𝑦)。
So for the scalar, I got :所以对于标量,我得到:
def scalar_function(x, y):
if x <= y:
return x*y
else:
return x/y
For the vector function I have :对于向量函数,我有:
def vector_function(x, y):
vfunc = np.vectorize(scalar_function, otypes = [float])
return vfunc
From here on I am stuck.从这里开始,我被困住了。
尝试这个
vector_function = np.vectorize(scalar_function)
based on this 'Please write a vector function vector_function, which will apply the operation 𝑓(𝑥,𝑦) defined above element-wisely with input vectors with same dimension x and y'
here is what you are looking for:基于这个
'Please write a vector function vector_function, which will apply the operation 𝑓(𝑥,𝑦) defined above element-wisely with input vectors with same dimension x and y'
这里是你正在寻找的:
import numpy as np
def scalar_function(x, y):
if x <= y:
return x*y
else:
return x/y
vector_function = np.vectorize(scalar_function, otypes = [float])
print(vector_function(np.array([1, 2, 3, 6]), np.array([1, 3, 4, 5])))
[Output]>>> [ 1. 6. 12. 1.2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.