将上三角条目的平面列表复制到完整矩阵? [英] Copy flat list of upper triangle entries to full matrix?
问题描述
我在平面列表(连接的行)中具有对称矩阵的上三角条目(包括对角线),并且我想使用它们来填充完整的矩阵,包括下三角.最快的方法是什么?
I have the upper triangle entries (including diagonal) of a symmetric matrix in a flat list (concatenated rows), and I want to use them to fill in the full matrix, including the lower triangle. What's the fastest way to do this?
这是我目前的做法.如此简单的操作似乎需要做很多工作.
Here is my current approach. Seems like a lot of work for such a simple operation.
import numpy as np
def utri2mat(utri,ntotal):
iu1 = np.triu_indices(ntotal)
ret = np.zeros([ntotal,ntotal])
ret[iu1] = utri
ret = ret + ret.transpose() - np.diag(ret.diagonal())
return ret
推荐答案
这是我提名的一种更快,甚至可能更好的方法,用于根据平面值制作对称矩阵:
Here's my nomination for a faster, and possibly better, way to make a symmetric matrix from flat values:
def make_sym(val, n):
# uses boolean mask
# uses the same lower tri as np.triu
mask = ~np.tri(5,k=-1,dtype=bool)
out = np.zeros((n,n),dtype=val.dtype)
out[mask] = val
out.T[mask] = val
return out
测试:
In [939]: val=np.arange(1,16)
In [940]: make_sym(val, 5)
Out[940]:
array([[ 1, 2, 3, 4, 5],
[ 2, 6, 7, 8, 9],
[ 3, 7, 10, 11, 12],
[ 4, 8, 11, 13, 14],
[ 5, 9, 12, 14, 15]])
与其他答案一样,它使用out.T[]
分配下部三角形.
Like the other answers it uses out.T[]
to assign the lower triangle.
Warren的答案使用np.triu_indices
,即where
值.这种类型的索引比布尔掩码慢一点.
Warren's answer uses np.triu_indices
, which are the where
values. This type of indexing is a bit slower than boolean masking.
但是正如我提到的,Divakar使用的np.triu
在早期的numpy
版本(例如1.9)中不会返回布尔掩码.这就是促使我深入研究问题的原因.
But as I noted the np.triu
that Divakar uses does not return a boolean mask in earlier numpy
versions (e.g. 1.9). This is what prompted me to dig into the issue.
在1.10中,此函数被重写为:
In 1.10 this function was rewritten as:
mask = np.tri(*m.shape[-2:], k=k-1, dtype=bool)
return np.where(mask, np.zeros(1, m.dtype), m)
通过将where
替换为~mask
,我获得了一些速度.结果相同,但只是删除了一个中间步骤.
I gain a bit of speed by replacing the where
with ~mask
. Same result, but just cutting out an intermediate step.
这篇关于将上三角条目的平面列表复制到完整矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!