简体   繁体   English

如何构造一个简单的矩阵并根据方程(numpy)更改值?

[英]How to construct a simple matrix and change values according to equation (numpy)?

My question is really simple.我的问题很简单。 I have to make a 5*5 matrix and each i,j value should follow a formula of i+j我必须制作一个 5*5 的矩阵,每个 i,j 值都应该遵循 i+j 的公式

I have this so far: '''到目前为止我有这个:'''

 w = np.zeros(shape=(5,5)) print(w) for i in range(5): for j in range(5): w[i][j] == i**2+j print(w)

But Its just returning a 0 matrix right now what to do ?但它现在只是返回一个 0 矩阵怎么办?

Just change只是改变

w[i][j] == i**2+j

to (if you want to keep the formular)到(如果你想保留公式)

w[i,j] = i**2+j

or use the formular from your question或使用您问题中的公式

w[i,j] = i+j

If you want to get rid of the loops, you can use numpy如果你想摆脱循环,你可以使用 numpy

w = np.arange(5)
w = np.add.outer(w ** 2, w)
print(w)

Out:出去:

[[ 0  1  2  3  4]
 [ 1  2  3  4  5]
 [ 4  5  6  7  8]
 [ 9 10 11 12 13]
 [16 17 18 19 20]]

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

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