我有一个上、下对角三角矩阵,我想合并它们,但还要添加一个 1 的对角线。
这是我所拥有的...
upper = np.array([[0.90858992, 0.96590361, 0.95616282],
[ np.nan, 0.90055735, 0.8956839 ],
[ np.nan, np.nan, 0.94590614]])
还有较低的...
lower = np.array([[0.90858992, np.nan, np.nan ],
[0.96590361, 0.90055735, np.nan ],
[0.95616282, 0.8956839 , 0.94590614]])
这就是我想要制作的:
np.array([
[1, 0.90858992, 0.96590361, 0.95616282 ],
[0.90858992, 1, 0.90055735, 0.8956839],
[0.96590361, 0.90055735, 1, 0.94590614 ],
[0.95616282, 0.8956839 , 0.94590614, 1 ]])
有人对我如何实现这个预期结果有任何建议吗?我尝试过矩阵加法,但似乎无法使其工作
可以从单位矩阵开始,然后填充上/下三角部分。
要访问输入矩阵和输出矩阵的上/下三角部分,您可以使用
np.triu_indices
和 np.tril_indices
。
以下代码应创建预期的
out
数组。
n = len(upper) + 1
out = np.eye(n)
out[np.triu_indices(n, 1)] = upper[np.triu_indices(n-1)]
out[np.tril_indices(n, -1)] = lower[np.tril_indices(n-1)]
import numpy as np
upper = np.array([[1, 2, 3],
[np.nan, 4, 5],
[np.nan, np.nan, 6]])
lower = np.array([[1, np.nan, np.nan],
[2, 4, np.nan],
[7, 5, 6]])
# Determine the size of the full matrix
n = upper.shape[0] + 1
# Create the full matrix with NaNs initially
full_matrix = np.full((n, n), np.nan)
# Create masks for the upper and lower triangular parts
upper_mask = np.triu(np.ones((n, n), dtype=bool), 1)
lower_mask = np.tril(np.ones((n, n), dtype=bool), -1)
# Assign values to the upper triangular part
full_matrix[upper_mask] = upper[np.triu_indices(upper.shape[0])]
# Assign values to the lower triangular part
full_matrix[lower_mask] = lower[np.tril_indices(lower.shape[0])]
# Fill the diagonal with 1s
np.fill_diagonal(full_matrix, 1)
print(full_matrix)
[[1. 1. 2. 3.]
[1. 1. 4. 5.]
[2. 4. 1. 6.]
[7. 5. 6. 1.]]