8

使用numpy包生成反对角线上全为1的矩阵

 3 years ago
source link: https://blog.csdn.net/u011699626/article/details/112001555
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

使用numpy包生成反对角线上全为1的矩阵

前几天突然有了一个想法,就是numpy包中有很多函数可以用来生成对角矩阵,然而有没有办法能够生成反对角矩阵呢?虽然我们知道生成反对角矩阵在数学上是没有意义的,例如:反对角全为1的矩阵实际上只与主对角线上全为1的矩阵相差一个负号。然而只是单纯的好奇,就研究了一下,这里给出解答。

import numpy as np


class Debug:
    @staticmethod
    def mainProgram():
        x = np.eye(3)
        print("主对角线全为1的矩阵")
        print(x)
        for line in x:
            length = len(x)
            for i in range(int(length / 2)):
                line[i], line[length - 1 - i] = line[length - 1 - i], line[i]
        print("反对角线全为1的矩阵")
        print(x)


if __name__ == '__main__':
    debug = Debug()
    debug.mainProgram()
"""
主对角线全为1的矩阵
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
反对角线全为1的矩阵
[[0. 0. 1.]
 [0. 1. 0.]
 [1. 0. 0.]]
"""

至此,我们看到,成功生成了反对角线上全为1的矩阵。(BTW: 没有难度,我能打十个,哈哈哈)

如果大家觉得有用,请高抬贵手给一个赞让我上推荐让更多的人看到吧~


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK