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

如何使用np.ix_实现4×4矩阵运算并插入10×10大矩阵

4×4矩阵插入10×10矩阵的实现方案

首先明确小矩阵的插入位置:假设小矩阵左上角对齐大矩阵的start_row行start_col列(numpy默认从0开始计数),小矩阵覆盖的行范围为start_row ~ start_row+3,列范围为start_col ~ start_col+3。

核心实现代码

import numpy as np

# 1. 初始化10×10大矩阵,可根据需求修改初始值
big_matrix = np.zeros((10, 10), dtype=int)
# 2. 定义待插入的4×4小矩阵,可替换为你的实际矩阵
small_matrix = np.arange(1, 17).reshape(4, 4)

# 3. 自定义插入起始坐标,示例为从第2行第3列开始插入
start_row = 2
start_col = 3

# 4. 生成索引网格并完成赋值
insert_rows = np.arange(start_row, start_row + 4)
insert_cols = np.arange(start_col, start_col + 4)
big_matrix[np.ix_(insert_rows, insert_cols)] = small_matrix

错误原因说明

你之前得到错误输出,大概率是直接使用了big_matrix[insert_rows, insert_cols] = small_matrix的写法:这种写法下numpy会将两个一维索引数组按位置配对,仅修改4个对角位置的元素,无法完成整块赋值。
np.ix_的作用是将一维的行、列索引数组转换为可广播的二维网格结构,行索引会变成(4,1)维度,列索引会变成(1,4)维度,广播后刚好匹配4×4小矩阵的维度,实现整块区域的赋值。

结果验证

你可以通过切片打印插入区域验证结果:

print(big_matrix[start_row:start_row+4, start_col:start_col+4])

输出内容与你的小矩阵完全一致即为操作成功。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 14:54:04