【问题标题】:How do I make a hollow symmetric matrix with zeros in the main diagonal, ones elsewhere in numpy如何制作一个空心对称矩阵,主对角线为零,numpy其他地方为零
【发布时间】:2017-10-09 22:22:03
【问题描述】:

在 Python numpy 中,如何制作一个空心对称矩阵,主对角线为零,其他地方为零?例如

import numpy as np
I = np.identity(8)  # the identity matrix
I

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

但我想要::

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

【问题讨论】:

    标签: python numpy matrix linear-algebra identity


    【解决方案1】:

    只需从 1 中减去单位矩阵:

    1 - np.identity(size)
    

    演示:

    In [3]: np.identity(4)
    Out[3]: 
    array([[ 1.,  0.,  0.,  0.],
           [ 0.,  1.,  0.,  0.],
           [ 0.,  0.,  1.,  0.],
           [ 0.,  0.,  0.,  1.]])
    
    In [4]: 1 - np.identity(4)
    Out[4]: 
    array([[ 0.,  1.,  1.,  1.],
           [ 1.,  0.,  1.,  1.],
           [ 1.,  1.,  0.,  1.],
           [ 1.,  1.,  1.,  0.]])
    

    【讨论】:

    • 哦,这很简单,感觉有点愚蠢!哈哈。坦克为您快速解答!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多