numpy 给定一个大小为3 x 3的矩阵,找出每一行的最大数,比如N1、N2和N3

hrirmatl  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(113)

给定一个大小为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

我被困在这里

f45qwnt8

f45qwnt81#

您可以使用np.trinp.eye为所需的不同区域创建遮罩。np.select用于填写正确的值!

upper = ~np.tri(3, dtype=bool)
diag = np.eye(3, dtype=bool)
lower = np.tri(3, k=-1)

values = np.select([upper, diag, lower], mat.max(axis=0))

out = mat + values

输出:

>>> upper
array([[False,  True,  True],
       [False, False,  True],
       [False, False, False]])
>>> diag
array([[ True, False, False],
       [False,  True, False],
       [False, False,  True]])
>>> lower
array([[False, False, False],
       [ True, False, False],
       [ True,  True, False]])
>>> values
array([[20, 10, 10],
       [30, 20, 10],
       [30, 30, 20]])
>>> out
array([[30, 15, 19],
       [32, 40, 16],
       [38, 33, 50]])
fjnneemd

fjnneemd2#

这个答案假设你说的“上半部分”和“下半部分”是指upper and lower triangular matrices
您已经知道如何正确获得行最大值。接下来,您需要:

  • N1添加到mat的上半部分元素。您可以使用np.triu_indices来获取正确的索引,并将N1添加到这些索引中:
upper_indices = np.triu_indices(mat.shape[0], 1)
mat[upper_indices] += N1

triu_indices的第二个参数指定三角矩阵开始的对角线上方的偏移量。

diag_indices = np.diag_indices(mat.shape[0])
mat[diag_indices] += N2
  • N3添加到mat的下半部分元素。您可以使用np.tril_indices来获取正确的索引,并将N3添加到这些索引中:
lower_indices = np.tril_indices(mat.shape[0], -1)
mat[lower_indices] += N3

tril_indices的第二个参数也指定了你想要开始三角矩阵的对角线上方的偏移量,所以它需要是-1才能开始对角线下方的三角矩阵。这导致了下面的mat

array([[30, 15, 19],
       [32, 40, 16],
       [38, 33, 50]])

相关问题