简体   繁体   English

建立一个numpy矩阵

[英]Building a numpy matrix

I'm trying to build a matrix in numpy. 我正在尝试在numpy中构建矩阵。 The matrix dimensions should be (5001x7). 矩阵尺寸应为(5001x7)。 Here is my code: 这是我的代码:

S=np.array([.0788,.0455,.0222,.0042,.0035,.0029,.0007])
#This is vector S, comprised of 7 scalars.

lamb=list(range(0,5001))
#This is a list of possible values for lambda, a parameter in my data.

M = np.empty([5001,7], order='C')
#This is the empty matrix which is to be filled in the iterations below.

for i in S:
    for j in lamb:
         np.append(M,((S[i]**2)/(lamb[j]+S[i]**2)))

The problem I'm having is that M remains a matrix of zero vectors. 我遇到的问题是M仍然是零向量的矩阵。

Important details: 1) I've assigned the final line as: 重要细节:1)我将最后一行指定为:

    M=np.append(M,((S[i]**2)/(lamb[j]+S[i]**2)))

I then get an array of values of length 70,014 in a 1d array. 然后,我在一维数组中得到一个长度为70,014的值的数组。 I'm not really sure what to make of it. 我不太确定该怎么做。

2) I've already tried switching the dtype parameter between 'float' and 'int' for matrix M. 2)我已经尝试过在矩阵M的'float'和'int'之间切换dtype参数。

3) I receive this warning when I run the code: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future app.launch_new_instance() 3)我在运行代码时收到此警告:VisibleDeprecationWarning:使用非整数而不是整数会在以后的app.launch_new_instance()中导致错误。

4) I'm working in Python 3.4 4)我正在使用Python 3.4

I really appreciate your help. 非常感谢您的帮助。 Thank you! 谢谢!

np.append makes a copy of the array and appends values to the end of the copy (making the array larger each time), whereas I think you want to modify M in place: np.append制作数组的副本,并将值附加到副本的末尾(每次使数组变大),而我认为您想就地修改M

 for i in range(len(S)):
     for j in range(len(lamb)):
          M[j][i] = ((S[i]**2)/(lamb[j]+S[i]**2))

1) append adds to the end of the array, which is why your final array has 5001x7x2=70014 elements. 1) append添加到数组的末尾,这就是为什么最终数组具有5001x7x2=70014元素的原因。 Only the first half is zeros. 仅前半部分为零。 It flattens the array to 1D because you didn't specify an axis to append. 由于未指定要附加的axis ,因此将数组展平为1D。

2) A much more "numpy" way to do this whole process is broadcasting 2)完成整个过程的另一种“麻木”方法是广播

S=np.array([.0788,.0455,.0222,.0042,.0035,.0029,.0007])
lamb=np.arange(0,5001)
M=(S[:,None]**2)/(lamb[None,:]+S[:,None]**2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM