2
import numpy as np
dx = 8
dy = 10
bx = 5.34
by = 1.09
index = np.zeros((dx+dy),dtype = 'int32')
for i in np.arange(1,dy+1):
    for j in np.arange (1,dx+1):
        if i-by > 0:
            theta = 180*np.arctan(abs(j-bx)/(i-by))/np.pi
            if theta<10:
                r = np.around(np.sqrt((j-bx)**2+(i-by)**2))
                r = r.astype(int)               
                if r>0:
                    index[r]+=1
                    output = np.zeros((r, index[r]),dtype='int32')
                    output[r-1,index[r]-1] = i+(j-1)*dy

此代码应使用 (r, index[r]) 作为索引,并将 i+(j-1)*dy 的值放入相应的索引中,并将其记录在一个新的矩阵/数组中,该矩阵/数组应如下所示 -

array([[ 0,  0,  0],
   [ 0,  0,  0],
   [44,  0,  0],
   [45, 55,  0],
   [46, 56,  0],
   [47, 57,  0],
   [48, 58,  0],
   [39, 49, 59],
   [40, 50, 60]]) 

但我有这样的输出,而不是我不想要的 -

array([[ 0,  0,  0],
   [ 0,  0,  0],
   [ 0,  0,  0],
   [ 0,  0,  0],
   [ 0,  0,  0],
   [ 0,  0,  0],
   [ 0,  0,  0],
   [ 0,  0,  0],
   [ 0,  0, 60]])
4

1 回答 1

0

很难说出的代码试图做什么。您想要的输出应该是s,c还是index?

或者,也许您想创建一个新数组,我会调用它output,然后您可以将outputat的值设置scusing: output[s] = c

如果您事先不知道大小,那么我现在能想到的最好的事情就是跟踪 and 列表中的所有索引值,以及 列表中rowscols实际值values

import numpy as np
dx = 8
dy = 10
bx = 5.34
by = 1.09
index = np.zeros(dx+dy,dtype = 'int32')
rows = []
cols = []
vals = []
for i in np.arange(2,dy+1):
    for j in np.arange(1,dx+1):
        theta = 180*np.arctan(abs(j-bx)/(i-by))/np.pi
        if theta < 10:
            r = np.around(np.sqrt((j-bx)**2+(i-by)**2))
            r = r.astype(int) 
            if r > 0:
                index[r] += 1
                rows.append(r-1)
                cols.append(index[r]-1)
                vals.append(i+(j-1)*dy)

outshape = max(rows)+1, max(cols)+1  # now you know the size
output = np.zeros(outshape, np.int)  
output[rows, cols] = vals

然后,output看起来像这样:

In [60]: output
Out[60]: 
array([[ 0,  0,  0],
       [ 0,  0,  0],
       [44,  0,  0],
       [45, 55,  0],
       [46, 56,  0],
       [47, 57,  0],
       [48, 58,  0],
       [39, 49, 59],
       [40, 50, 60]])

如果您事先知道尺寸:

import numpy as np
dx = 8
dy = 10
bx = 5.34
by = 1.09
index = np.zeros(dx+dy,dtype = 'int32')
outshape = (nrows, ncols)                        # if you know the size
output = np.zeros(outshape, np.int)              # initialize the output matrix
for i in np.arange(2,dy+1):
    for j in np.arange(1,dx+1):
        theta = 180*np.arctan(abs(j-bx)/(i-by))/np.pi
        if theta < 10:
            r = np.around(np.sqrt((j-bx)**2+(i-by)**2))
            r = r.astype(int) 
            if r > 0:
                index[r] += 1
                output[r-1, index[r]-1] = i+(j-1)*dy  # no need to set `s` or `c`
于 2013-05-06T15:28:07.307 回答