【问题标题】:Input numbers on diagonals of matrix在矩阵的对角线上输入数字
【发布时间】:2021-12-10 13:32:49
【问题描述】:

我需要使用矩阵。您应该能够在矩阵中输入数字(例如,如果我需要在对角线上有 1 并且在对角线上有 0.6,我可以输入它,0.6 只在对角线下方的线上)。它有一个简单的解决方案,但是当我还想编辑矩阵的大小时会变得很棘手。

我正在使用 numpy 库

【问题讨论】:

  • 你能否提供一些你已经完成的例子,以及输入和输出应该是什么样的。

标签: python numpy matrix


【解决方案1】:

如果你想要这样的矩阵:

[1. , 0.6, 0.6, 0.6, 0.6]
[0.6, 1. , 0.6, 0.6, 0.6]
[0.6, 0.6, 1. , 0.6, 0.6]
[0.6, 0.6, 0.6, 1. , 0.6]
[0.6, 0.6, 0.6, 0.6, 1. ]
import numpy as np

# First, you create a matrix full of the numbers outside the diagonal (let's use 5 as an example of the matrix' shape)

matrix = np.full((5,5),0.6)

# Then, you can edit the diagonal but using "numpy.diag_indices_from":

matrix[np.diag_indices_from(matrix)] = 1

print(matrix)

输出:

array([[1. , 0.6, 0.6, 0.6, 0.6],
       [0.6, 1. , 0.6, 0.6, 0.6],
       [0.6, 0.6, 1. , 0.6, 0.6],
       [0.6, 0.6, 0.6, 1. , 0.6],
       [0.6, 0.6, 0.6, 0.6, 1. ]])

【讨论】:

  • 谢谢,但是有什么方法可以访问对角线下的数字吗?我不知道所有的数字只是对角线下的线
  • @Jatel “对角线下的线”是指“其他对角线”吗?如果那是正确的,有一个关于这个问题的答案的帖子:stackoverflow.com/questions/6313308/…
猜你喜欢
  • 1970-01-01
  • 2016-05-02
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 2016-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多