4

I can only find results that use tuples of coordinates to assign certain values, like this one.

I want to assign values to a 2-dimensional array as a function of their coordinates. The simplest case would be to set the value of each element to their second index (e.g. x-coordinate). Such that,

x[0][0] = 0
x[1][0] = 0
...
x[2][0] = 0
x[0][1] = 1
x[0][2] = 2
...

More complex case would be to set these values to the Euclidean distance to a certain point (x, y).

My current solution is to use a for-loop, which is definitely not efficient. A vectorized implementation would be nice.

My current implementation:

x_mask = np.zeros((256, 256))
for i in range(256):
    for j in range(256):
        x_mask[i][j] = j
2
  • Your simple example is trivial. For more complex cases, you should try a vectorised solution yourself and tell us where you got stuck. There's no "generalized way" to vectorise an operation. If there was, we wouldn't need programmers :). Commented Jul 27, 2018 at 9:34
  • @jpp was expecting something like a lambda expression for each position. I guess it works equally well once I have x/y coordinates as helper matrix to compute a lot of other stuff. Commented Jul 27, 2018 at 9:37

3 Answers 3

4

You can assign a range and take advantage of NumPy broadcasting:

A = np.zeros((256, 256))
A[:] = range(A.shape[1])
# or A[:] = np.arange(A.shape[1])

The method you choose will be dependent on the function you wish to apply.

Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly. Getting Euclidean/Manhattan distance would be easy once I have the x/y coordinates too, thank you!
2

numpy.mgrid seems to be the right tool for this (especially if you want both x and y).

Example copied from the documentation:

>>> np.mgrid[0:5,0:5]
array([[[0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1],
        [2, 2, 2, 2, 2],
        [3, 3, 3, 3, 3],
        [4, 4, 4, 4, 4]],
       [[0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4]]]) 

Comments

-1

Try this :

a=[]
for i in range(4):
    b=[]
    for j in range(4):
        b.append(j)
    a.append(b)

1 Comment

..I don't want to use for-loop as stated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.