变换对称矩阵(二维数组)的上/下三角部分成一维数组,并返回到2D格式 [英] transform the upper/lower triangular part of a symmetric matrix (2D array) into a 1D array and return it to the 2D format

查看:777
本文介绍了变换对称矩阵(二维数组)的上/下三角部分成一维数组,并返回到2D格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题它解释了如何访问 triagular给定矩阵的部分,说:

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])

做了很多的计算与后 A ,改变它的价值,它会被用来填补对称的二维数组:

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]

返回:

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

有没有更好的方式来做到这一点?更多especifically,避免了Python循环重建二维数组?

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.]])

这篇关于变换对称矩阵(二维数组)的上/下三角部分成一维数组,并返回到2D格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆