简体   繁体   English

如何编写 numpy function 在 python 中将它的第 k 对角线返回为 0?

[英]how to write numpy function which returns it's kth diagonal as 0 in python?

NumPy function which takes a matrix and an integer k as parameters and returns a copy of this matrix such that all its elements under the kth diagonal are zero. NumPy function 采用一个矩阵和一个 integer k 作为参数,并返回该矩阵的副本,使其第 k 条对角线下的所有元素都为零。 The main diagonal is the 0th one, the diagonal above it are numbered 1, 2, .主对角线是第 0 条,它上面的对角线编号为 1、2、...。 . . ., and the diagonal below are numbered −1, −2, . .,下面的对角线编号为 -1、-2、. . . .. That is, 1 is the first diagonal above the main diagonal, 2 is the second diagonal above the main diagonal, etc. −1 is the first diagonal below the main diagonal, −2 is the second diagonal below the main diagonal. .. 也就是说,1 是主对角线上方的第一条对角线,2 是主对角线上方的第二条对角线,以此类推。-1 是主对角线下方的第一条对角线,-2 是主对角线下方的第二条对角线。

example:例子: 在此处输入图像描述

I think I figured out how to do a diagonal line, but then I am stuck:我想我想出了如何做对角线,但后来我被卡住了:

def EX4(N):
Z=np.zeros((N,N))  #create a array N x N which contains only zero elements


#Set the diagonal to 1
for i in range(k,N):
     Z[i,i]=1 
return Z

k=1 EX4(5) k=1 EX4(5)

You are probably looking for numpy.triu() , which supports exactly this behavior.您可能正在寻找numpy.triu() ,它完全支持这种行为。

>>> import numpy as np
>>> x = np.array([[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1]])
>>> np.triu(x, 0)
array([[1, 1, 1, 1, 1],
       [0, 1, 1, 1, 1],
       [0, 0, 1, 1, 1],
       [0, 0, 0, 1, 1],
       [0, 0, 0, 0, 1]])
>>> np.triu(x, 1)
array([[0, 1, 1, 1, 1],
       [0, 0, 1, 1, 1],
       [0, 0, 0, 1, 1],
       [0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0]])
>>> np.triu(x, 2)
array([[0, 0, 1, 1, 1],
       [0, 0, 0, 1, 1],
       [0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])

You can do something along the lines of the following.您可以按照以下方式进行操作。

z = np.zeros((4,4))

def f(k):
    for i in range(4):
        for j in range(4):
            if j > i + k:
                z[i,j] = 1

Edit: Just seen the other answer.编辑:刚刚看到另一个答案。 I wasn't aware numpy had this functionality.我不知道 numpy 有这个功能。 It would be best to use numpy's methods, however I will leave the answer here still if you were curious for a way to do it yourself.最好使用 numpy 的方法,但是如果您对自己的方法感到好奇,我会在这里留下答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM