【问题标题】:creating nxn matrix of special structure in numpy: sum of identity matrix and the same matrix shifted rightward by 1 column在numpy中创建特殊结构的nxn矩阵:单位矩阵和相同矩阵向右移动1列的总和
【发布时间】:2020-12-24 05:45:04
【问题描述】:

给定一个整数n,我想制作n x n以下形式的numpy矩阵。

对于n =4

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

对于n= 5

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

在数学上,它是将单位矩阵与一个矩阵相加,该矩阵本质上是单位矩阵向右移动 1 列。这是分解的示例。

如何在numpy 中执行此操作,其中输入为n

【问题讨论】:

    标签: python pandas numpy matrix numpy-ndarray


    【解决方案1】:

    检查numpyroll

    n = 3
    a1 = np.diag(np.full(n, 1))
    out = a1+np.roll(a1,shift=1, axis=1)
    out
    Out[21]: 
    array([[1, 1, 0],
           [0, 1, 1],
           [1, 0, 1]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      • 2014-07-15
      • 2022-12-12
      • 1970-01-01
      • 1970-01-01
      • 2013-01-24
      • 2014-11-08
      相关资源
      最近更新 更多