【问题标题】:How to make a matrix to the power of a number under some conditions without using loops in Python?如何在不使用 Python 循环的情况下在某些条件下生成一个数字的幂的矩阵?
【发布时间】:2016-04-28 19:24:40
【问题描述】:

我想在 python 中计算这个简单的代码,给定一个矩阵,根据它的条目修改它。如果(i, j)-th 条目大于或等于1,则使其为a 的幂,否则为1

import numpy 

def restricted_power(k, n, d, a):
    """
    :param d: a distance matrix
    :param k, n: shape of d
    :param a: a positive real number 
    :return: a modified distance matrix 
    """
    x = numpy.zeros((k,n))
    for i in range(k):
        for j in range(n):
            if d[i, j] < 1:
                x[i, j] = 1
            else: 
                x[i, j] = d[i, j] ** a
    return x

有没有办法在没有循环的情况下对此进行编码?

【问题讨论】:

  • 什么是 x?为什么要在没有循环的情况下解决这个问题?

标签: python loops if-statement matrix


【解决方案1】:

嗯,在某些时候没有循环是不可能的,但是你可以用 numpy 将循环推送到 C 层。

>>> import numpy as np
>>> example = np.arange(9).reshape(3,3)/4.0
>>> example
array([[ 0.  ,  0.25,  0.5 ],
       [ 0.75,  1.  ,  1.25],
       [ 1.5 ,  1.75,  2.  ]])
>>> a = 2 # sample exponent
>>> np.where(example < 1, 1, example**a)
array([[ 1.    ,  1.    ,  1.    ],
       [ 1.    ,  1.    ,  1.5625],
       [ 2.25  ,  3.0625,  4.    ]])

【讨论】:

    猜你喜欢
    • 2017-09-05
    • 2015-09-05
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多