Getting diagonal matrix stripe automatically in numpy or pytorch

后端 未结 2 1870
甜味超标
甜味超标 2021-01-14 10:11

I need to get a diagonal stripe of the matrix (not sure about the terminology here, diagonal matrix stripe seems to describe it best).

Say, I have a matrix of size K

2条回答
  •  我在风中等你
    2021-01-14 10:39

    Extending Paul's answer. You can do the same in PyTorch using diag multiple times (I do not think there is any direct function to do strides in PyTorch)

    In [1]: import torch
    
    In [2]: def stripe(a):
       ...:     i, j = a.size()
       ...:     assert(i>=j)
       ...:     out = torch.zeros((i-j+1, j))
       ...:     for diag in range(0, i-j+1):
       ...:         out[diag] = torch.diag(a, -diag)
       ...:     return out
       ...: 
    
    In [3]: a = torch.randn((6, 3))
    
    In [4]: a
    Out[4]: 
    
     0.7669  0.6808 -0.6102
    -1.0624 -1.2016 -0.7308
     1.4054 -1.0621  0.2618
    -0.9505 -0.9322 -0.4321
    -0.0134 -1.3684  0.1883
    -0.8499  0.2533 -0.3976
    [torch.FloatTensor of size 6x3]
    
    In [5]: stripe(a)
    Out[5]: 
    
     0.7669 -1.2016  0.2618
    -1.0624 -1.0621 -0.4321
     1.4054 -0.9322  0.1883
    -0.9505 -1.3684 -0.3976
    [torch.FloatTensor of size 4x3]
    

提交回复
热议问题