python - Python 可以执行矢量化操作吗?

标签 python numpy scipy

我想在 Python 中实现以下 Matlab 代码:

x=1:100;
y=20*log10(x);

我尝试使用 Numpy 来执行此操作:

y = numpy.zeros(x.shape)
for i in range(len(x)):
    y[i] = 20*math.log10(x[i])

但这使用了一个for循环;有没有像在 Matlab 中那样做矢量化操作?我知道对于一些简单的数学运算,例如除法和乘法,这是可能的。但是这里的对数等其他更复杂的运算呢?

最佳答案

y = numpy.log10(numpy.arange(1, 101)) * 20

In [30]: numpy.arange(1, 10)
Out[30]: array([1, 2, 3, 4, 5, 6, 7, 8, 9])

In [31]: numpy.log10(numpy.arange(1, 10))
Out[31]:
array([ 0.        ,  0.30103   ,  0.47712125,  0.60205999,  0.69897   ,
        0.77815125,  0.84509804,  0.90308999,  0.95424251])

In [32]: numpy.log10(numpy.arange(1, 10)) * 20
Out[32]:
array([  0.        ,   6.02059991,   9.54242509,  12.04119983,
        13.97940009,  15.56302501,  16.9019608 ,  18.06179974,  19.08485019])

关于python - Python 可以执行矢量化操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15774705/

相关文章:

Python:获取 shell 命令的输出 'history'

python - 如何将 SqlAlchemy 结果序列化为 JSON?

python - Numpy 过滤器像素索引

python - 使用 vispy/scipy 时无法卡住应用程序

python - 哪个更好 - 将玩家的库存存储在 JSON(数据库中的文本字段)或直接数据库中?

python - Tensorflow tf.layers 密集神经网络函数与类接口(interface)

python - 替代以 numpy 数组作为边界的排列

python - Pandas 数据帧索引的 itertools.permutations 使用了太多内存

python - 最小化函数,如何将参数传递给函数 scipy

python - 两个仅影响零值的稀疏矩阵的点积