python二维数组输出下三角,变换对称矩阵(二维数组)的上/下三角部分成一维数组,并返回到2D格式...

In this question it is explained how to access the lower and upper triagular parts of a given matrix, say:

m = np.matrix([[11, 12, 13],

[21, 22, 23],

[31, 32, 33]])

Here I need to transform the matrix in a 1D array, which can be done doing:

indices = np.triu_indices_from(m)

a = np.asarray( m[indices] )[-1]

#array([11, 12, 13, 22, 23, 33])

After doing a lot of calculations with a, changing its values, it will be used to fill a symmetric 2D array:

new = np.zeros(m.shape)

for i,j in enumerate(zip(*indices)):

new[j]=a[i]

new[j[1],j[0]]=a[i]

Returning:

array([[ 11., 12., 13.],

[ 12., 22., 23.],

[ 13., 23., 33.]])

Is there a better way to accomplish this? More especifically, avoiding the Python loop to rebuild the 2D array?

解决方案

Do you just want to form a symmetric array? You can skip the diagonal indices completely.

>>> m=np.array(m)

>>> inds = np.triu_indices_from(m,k=1)

>>> m[(inds[1], inds[0])] = m[inds]

>>> m

array([[11, 12, 13],

[12, 22, 23],

[13, 23, 33]])

Creating a symmetric array from a:

>>> new = np.zeros((3,3))

>>> vals = np.array([11, 12, 13, 22, 23, 33])

>>> inds = np.triu_indices_from(new)

>>> new[inds] = vals

>>> new[(inds[1], inds[0])] = vals

>>> new

array([[ 11., 12., 13.],

[ 12., 22., 23.],

[ 13., 23., 33.]])

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值