def make_triangular_matrix(values):
# Compute the appropriate side length for the given input ...
# good old quadratic equation :-)
n = (np.sqrt(8*len(values) + 1) - 1) / 2
if not n.is_integer(): raise Exception("Invalid input length")
side_length = int(n) + 1
out = np.zeros((side_length, side_length), dtype=values.dtype)
# Only interested in the region BELOW the diagonal,
# which excludes the first row and last column ...
lower = out[1:,:-1]
# Assign the values to the appropriate indices (see note about .T)
lower.T[np.triu_indices_from(lower)] = values
return out
make_triangular_matrix(np.array([1,2,3,4,5,6,7,8,9,10]))
2条答案
按热度按时间50few1ms1#
另一种可能的解决方案:
输出:
y1aodyip2#
有点乱,但能完成任务:
请注意,在行为主模式中构造上三角区域更自然一些,这就是为什么我们使用上三角索引填充
lower.T
。