0

are there any numpy function or clever use of views to accomplish what the following function do?

 import numpy as np

 def permuteIndexes(array, perm):
     newarray = np.empty_like(array)
     max_i, max_j = newarray.shape
     for i in xrange(max_i):
         for j in xrange(max_j):
             newarray[i,j] = array[perm[i], perm[j]]
     return newarray

That is, for a given permutation of the indexes of the matrix in a list perm, this function calculates the result of applying this permutation to the indexes of a matrix.

1 Answer 1

6
def permutateIndexes(array, perm):
    return array[perm][:, perm]

Actually, this is better as it does it in a single go:

def permutateIndexes(array, perm):
    return array[np.ix_(perm, perm)]

To work with non-square arrays:

def permutateIndexes(array, perm):
    return array[np.ix_(*(perm[:s] for s in array.shape))]
2
  • hummm! I must to learn how to use those views properly. Is there any guide around? Aug 24, 2012 at 18:42
  • 1
    @RafaelS.Calsaverini definitely read the Tentative NumPy Tutorial if you haven't already.
    – ecatmur
    Aug 24, 2012 at 18:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.