2

I have 2 1d arrays of type int and a start and a stop value that look like this:

y_start = #some number
y_end = #some number
x_start = #some array of ints
x_end = #some array of ints

What I want is to simulate the following behavior without loops:

for i, y in enumerate(range(y_start, y_end)):
    arr[x_start[i]:x_end[i], y] = c

Example:

y_start = 2
y_end = 5
x_start = np.array([2, 1, 3])
x_end = np.array([4, 3, 6])
c = 1

Input

arr = array([[0, 0, 0, 0, 0, 0, 0],
             [0, 0, 0, 0, 0, 0, 0],
             [0, 0, 0, 0, 0, 0, 0],
             [0, 0, 0, 0, 0, 0, 0],
             [0, 0, 0, 0, 0, 0, 0],
             [0, 0, 0, 0, 0, 0, 0]])

Output:

arr = array([[0, 0, 0, 0, 0, 0, 0],
             [0, 0, 0, 1, 0, 0, 0],
             [0, 0, 1, 1, 0, 0, 0],
             [0, 0, 1, 0, 1, 0, 0],
             [0, 0, 0, 0, 1, 0, 0],
             [0, 0, 0, 0, 1, 0, 0]])

Would this be possible?

4
  • what does arr look like? Please provide an explicit complete example (input + output) Commented Sep 5, 2022 at 18:01
  • This is for triangle rasterization so arr is pretty big but ill put smaller example. Commented Sep 5, 2022 at 18:04
  • Yes, please use a minimal example (also provide the start/end values and the output) Commented Sep 5, 2022 at 18:07
  • Alright I did it. Commented Sep 5, 2022 at 18:12

1 Answer 1

4

You can use indexing and a crafted boolean arrays converted to integer:

v = np.arange(arr.shape[0])[:,None]
                                                  # conversion to int is implicit
arr[:, y_start:y_end] = ((v>=x_start) & (v<x_end))#.astype(int)

output:

array([[0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0],
       [0, 0, 1, 1, 0, 0, 0],
       [0, 0, 1, 0, 1, 0, 0],
       [0, 0, 0, 0, 1, 0, 0],
       [0, 0, 0, 0, 1, 0, 0]])
Sign up to request clarification or add additional context in comments.

Comments

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.