3

【丢弃】取上三角和下三角.

 2 years ago
source link: https://www.guofei.site/2017/04/29/case1.html
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.

【丢弃】取上三角和下三角.

2017年04月29日

Author: Guofei

文章归类: ,文章编号:


版权声明:本文作者是郭飞。转载随意,但需要标明原文链接,并通知本人
原文链接:https://www.guofei.site/2017/04/29/case1.html

Edit

这部分内容已经过时,因为np已经有取上三角矩阵和下三角矩阵的方法triu)

上三角和下三角矩阵

numpy中没有很方便的取上三角矩阵或下三角矩阵的方法

import numpy as np


def triu_ones(m, n, k=0):
    output = np.zeros((m, n))
    for i in range(k, max(m, n)):
        output += np.eye(m, n, i)
    return output


def tril_ones(m, n, k=0):
    output = np.zeros((m, n))
    for i in range(k, -max(m, n), -1):
        output += np.eye(m, n, i)
    return output


def triu_like(matrix, k=0):
    m, n = matrix.shape
    return triu_ones(m, n, k)


def tril_like(matrix, k=0):
    m, n = matrix.shape
    return tril_ones(m, n, k)


def triu(matrix, k=0):
    return matrix * triu_like(matrix=matrix, k=k)


def tril(matrix, k=0):
    return matrix * tril_like(matrix=matrix, k=k)


if __name__ == '__main__':
    print(triu_ones(5, 10, 1))
    print(triu_ones(10, 5, -1))
    print(tril_ones(5, 10, 1))
    print(tril_ones(10, 5, -1))


您的支持将鼓励我继续创作!

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK