给定一个大小为3 x 3的矩阵。找出每一行的最大数,比如N1、N2和N3。通过添加以下内容得到矩阵:
import numpy as np
mat = np.array([[10,5,9],
[2,20,6],
[8,3,30]]).reshape(3,3)
- N1至垫的上半部分元件
- N2至垫的主对角线元素
- N3至垫的下半部分元件
我的代码:
import numpy as np
mat = np.array([[10,5,9],
[2,20,6],
[8,3,30]]).reshape(3,3)
max_list = np.max(mat, axis=0)
N1 = max_list[0]
N2 = max_list[1]
N3 = max_list[2]
z_mat = np.zeros((3, 3), dtype=np.int32)
N1_mat = z_mat[0:2, 2:] = N1
我被困在这里
2条答案
按热度按时间f45qwnt81#
您可以使用
np.tri
和np.eye
为所需的不同区域创建遮罩。np.select
用于填写正确的值!输出:
fjnneemd2#
这个答案假设你说的“上半部分”和“下半部分”是指upper and lower triangular matrices。
您已经知道如何正确获得行最大值。接下来,您需要:
N1
添加到mat
的上半部分元素。您可以使用np.triu_indices
来获取正确的索引,并将N1
添加到这些索引中:triu_indices
的第二个参数指定三角矩阵开始的对角线上方的偏移量。N2
添加到mat
的对角线元素。可以使用np.diag_indices
N3
添加到mat
的下半部分元素。您可以使用np.tril_indices
来获取正确的索引,并将N3
添加到这些索引中:tril_indices
的第二个参数也指定了你想要开始三角矩阵的对角线上方的偏移量,所以它需要是-1
才能开始对角线下方的三角矩阵。这导致了下面的mat
: