简体   繁体   中英

put 2d coordinate axis at the center of an array in python

I am going to simulate a 2d area using a matrix in python and I should change the indexes somehow.. I need to find a relation between the original matrix and a new axis coordinate: I think it can be more clarified if I explain by a piece of my code:

originalMatrix=np.random.randint(0, 10, size=(5,5))

the output is:

[[4 8 3 2 5]
 [2 2 2 6 5]
 [2 4 7 9 9]
 [6 2 6 6 6]
 [2 8 3 8 2]]

we can access to number '7' by originalMatrix[2][2]. but in the coordinate system the index must be (0,0).Index of '4' in the left side of '7' in originalMatrix is [2][1] but in the new coordinate should be (-1,0) and so on... I hope I could explain well!

An easy way is to roll your array:

a = np.array([[4, 8, 3, 2, 5],
              [2, 2, 2, 6, 5],
              [2, 4, 7, 9, 9],
              [6, 2, 6, 6, 6],
              [2, 8, 3, 8, 2]])
center = np.array(a.shape)//2
# b will be indexed with the previous center being 0,0
b = np.roll(a, -center, axis=(0,1))

b[0, -1]
# 4

b[0, 0]
# 7

NB. You have to decide what is the center in case you have an even number as a dimension.

There is no way to do that with standard numpy arrays, but you could define a function that does it for you

def arrayByCoordinates(array, coords):
    coords = np.array(coords)
    center = np.array(array.shape) // 2
    return array[tuple(coords + center)]
>>> x
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])
>>> arrayByCoordinates(x,(0,0))
12

But keep in mind that if the shape of the array is even, there is no real center, so this will convert to the lowest one

Here is another possible approach, assuming the matrix is nxn where n is odd:

import numpy as np


def access_coordinate(matrix, x, y):
    center = (len(matrix)//2, len(matrix)//2)
    translated_coordinates = (center[0]+y, center[1] + x)
    return matrix[translated_coordinates[0], translated_coordinates[1]]
    

originalMatrix=np.array([[4, 8, 3, 2, 5],
 [2, 2, 2 ,6, 5],
 [2, 4, 7, 9, 9],
 [6, 2, 6, 6, 6],
 [2, 8, 3, 8, 2]])


print(access_coordinate(originalMatrix, -1, 0)) #4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM