jeudi 28 avril 2016

How to make a matrix to the power of a number under some conditions without using loops in Python?

I would like to compute this simple code in python, given a matrix modify it according to its entries. If the (i, j)-th entry is greater than or equal to 1 then make it to the power of a else make it 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

Is there a way to code this without the loops ?

Aucun commentaire:

Enregistrer un commentaire