python如何迭代生成矩阵_如何使用行和列上的迭代在Python中填充矩阵

So I have an array of 5 integers v and another of 10 integers v.

I have a 5 by 10 matrix P that I would want to fill so that (P)ij = v[i] + u[j]

I tried:

P = np.empty((len(asset_grid),len(asset_grid)))

for i in range(asset_grid):

for j in range(asset_grid):

P[i,j] = asset_grid[i] + asset_grid[j]

but it gives me an error

TypeError: only integer arrays with one element can be converted to an index

How should I be able to do this in Python. I apologize if my approach is too naive, I am used to Matlab and now slowly learning Python. Any help is appreciated.

解决方案

Broadcasting is what you want to do. Although for small arrays such as yours, it doesn't make a difference, it makes a significant difference with larger arrays:

>>> arr1 = np.arange(5)

>>> arr2 = np.arange(10,20)

>>> arr1[:,None] + arr2

array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],

[11, 12, 13, 14, 15, 16, 17, 18, 19, 20],

[12, 13, 14, 15, 16, 17, 18, 19, 20, 21],

[13, 14, 15, 16, 17, 18, 19, 20, 21, 22],

[14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])

Generally with numpy you want to avoid iteration over rows and columns and use vectorized/broadcasted operations. This is where speed improvements actually come from.

So, elaborating based on your comment:

Say P_ij is ith element of x raised to the 4th power minus jth element of y raised to 2nd power

In general, Python supports most arithmetical operations you would want in a vectorized way, using the usual Python operators:

>>> arr1[:, None]**4 - arr2**2

array([[-100, -121, -144, -169, -196, -225, -256, -289, -324, -361],

[ -99, -120, -143, -168, -195, -224, -255, -288, -323, -360],

[ -84, -105, -128, -153, -180, -209, -240, -273, -308, -345],

[ -19, -40, -63, -88, -115, -144, -175, -208, -243, -280],

[ 156, 135, 112, 87, 60, 31, 0, -33, -68, -105]])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值