本文介绍了Python可以执行向量化操作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在Python中实现以下Matlab代码:
I want to implement the following Matlab code in Python:
x=1:100;
y=20*log10(x);
我尝试使用Numpy来做到这一点:
I tried using Numpy to do this:
y = numpy.zeros(x.shape)
for i in range(len(x)):
y[i] = 20*math.log10(x[i])
但这使用了for循环;无论如何,像Matlab一样进行矢量化运算?我知道对于一些简单的数学运算(例如除法和乘法),这是可能的.但是其他更复杂的运算(如对数)在这里呢?
But this uses a for loop; is there anyway to do a vectorized operation like in Matlab? I know for some simple math such as division and multiplication, it's possible. But what about other more sophisticated operations like logarithm here?
推荐答案
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可以执行向量化操作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!