在numpy的阵列的所有值进行操作,引用i和j [英] Performing operations on all values of a numpy array, referencing i and j
问题描述
我试图由一个二维数组上施加的操作,以改善numpy的性能,问题是,在阵列中的每个元素的值取决于I,该元素j的位置。
显然,简单的方法是使用一个嵌套的循环,但我不知道是否有可能是由沿着这些线路引用np.indices什么更好的办法?这里是我的'笨'code:
对于法官在范围(1025):
因为我在范围内(1025):
PSI [I] [J] = A * math.sin((浮点(I + 1) - 5)* DI)* math.sin((浮点(J + 1) - 5)* DJ)
P [I] [J] = PCF *(math.cos(2 *浮动(I)* DI)+ math.cos(2 *浮动(J)* DJ))+ 50000。
既然你做你的两个阵列中乘法,可以使用的外功能,使用人气指数
来得到你的罪阵列后/ COS。
这样的事情(使用numpy的的三角函数,因为他们是矢量)
PSI_i = numpy.sin((人气指数(1,1026)-0.5)* DI)
PSI_j = numpy.sin((人气指数(1,1026)-0.5)* DJ)
PSI = A *外(PSI_i,PSI_j)P_i = numpy.cos(2 *人气指数(1,1026)* DI)
P_j = numpy.cos(2 *人气指数(1,1026)* DJ)
P = PCF *外(P_i,P_j)+ 50000
如果您的环境设置使用从numpy的进口*
或从pylab进口*
,那么你不吨需要那些 numpy的。
prefixes之前,请三角函数。我把它们放在从数学
的人,不会为这一做法的工作区分开来。
I am trying to improve numpy performance by applying operations on a 2d array, the problem is that the value at each element in the array depends on the i,j location of that element.
Obviously the easy way to do this is to use a nested for-loop, but I was wondering if there might be a better way by referencing np.indices or something along those lines? Here is my 'stupid' code:
for J in range(1025):
for I in range(1025):
PSI[I][J] = A*math.sin((float(I+1)-.5)*DI)*math.sin((float(J+1)-.5)*DJ)
P[I][J] = PCF*(math.cos(2.*float(I)*DI)+math.cos(2.*float(J)*DJ))+50000.
Since you're doing multiplication among your two arrays, you can use the outer function, after using arange
to get arrays of your sin/cos.
Something like this (use numpy's trig functions, since they're vectorized)
PSI_i = numpy.sin((arange(1,1026)-0.5)*DI)
PSI_j = numpy.sin((arange(1,1026)-0.5)*DJ)
PSI = A*outer(PSI_i, PSI_j)
P_i = numpy.cos(2.*arange(1,1026)*DI)
P_j = numpy.cos(2.*arange(1,1026)*DJ)
P = PCF*outer(P_i, P_j) + 50000
If your environment is set up using from numpy import *
or from pylab import *
, then you don't need those numpy.
prefixes before your trig functions. I kept them in to distinguish them from the math
ones, which won't work for this approach.
这篇关于在numpy的阵列的所有值进行操作,引用i和j的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!