You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用NumPy将低维矩阵扩展为高维矩阵并填充对角1?

解决方法

可以通过NumPy的切片赋值结合np.fill_diagonal方法实现,步骤简洁且无需手动拼接行:

  1. 先创建目标维度的零矩阵
  2. 将原矩阵A赋值到零矩阵的左上角区域
  3. 对新增的右下角子矩阵填充对角为1

完整代码示例

import numpy as np

# 原矩阵
A = np.array([[0, 1], [1, 0]])
# 目标维度
target_rows, target_cols = 5, 5

# 1. 创建目标大小的零矩阵
B = np.zeros((target_rows, target_cols), dtype=A.dtype)
# 2. 把A放到左上角
B[:A.shape[0], :A.shape[1]] = A
# 3. 填充新增的对角元素
np.fill_diagonal(B[A.shape[0]:, A.shape[1]:], 1)

print(B)

输出结果

[[0 1 0 0 0]
 [1 0 0 0 0]
 [0 0 1 0 0]
 [0 0 0 1 0]
 [0 0 0 0 1]]

这种方式完全依赖NumPy内置操作,避免了手动拆分、拼接矩阵的繁琐步骤,且能灵活适配任意原矩阵大小和目标维度。

内容的提问来源于stack exchange,提问作者Chrsi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 00:02:08