Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在某些情况下,如何在不使用Python中的循环的情况下使矩阵达到数字的幂?_Python_Loops_If Statement_Matrix - Fatal编程技术网

在某些情况下,如何在不使用Python中的循环的情况下使矩阵达到数字的幂?

在某些情况下,如何在不使用Python中的循环的情况下使矩阵达到数字的幂?,python,loops,if-statement,matrix,Python,Loops,If Statement,Matrix,我想用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

我想用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
导入numpy
def限制动力(k、n、d、a):
"""
:param d:距离矩阵
:参数k,n:d的形状
:参数a:正实数
:return:修改后的距离矩阵
"""
x=numpy.zero((k,n))
对于范围(k)内的i:
对于范围(n)内的j:
如果d[i,j]<1:
x[i,j]=1
其他:
x[i,j]=d[i,j]**a
返回x

有没有一种方法可以不用循环来编写代码

好吧,在某一点上没有循环是不可能的,但是你可以用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.    ]])
>>将numpy作为np导入
>>>示例=np.arange(9).重塑(3,3)/4.0
>>>范例
数组([[0,0.25,0.5],
[ 0.75,  1.  ,  1.25],
[ 1.5 ,  1.75,  2.  ]])
>>>a=2#样本指数
>>>式中(示例<1,1,示例**a)
数组([[1,1,1.],
[ 1.    ,  1.    ,  1.5625],
[ 2.25  ,  3.0625,  4.    ]])

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