0

Let's say I have a numpy array like this (positions_full) which load some coordinate data like 2.5 or 8.2. I now wanted to loop that array through the def isInside. How can I do this?

positions_full = np.loadtxt('positions.txt')

x = positions_full[:,0]

y = positions_full[:,1]  

def isInside(circle_x, circle_y, rad, x, y):

    if ((x - circle_x) * (x - circle_x) +

        (y - circle_y) * (y - circle_y) <= rad * rad):

        return True;

    else:

        return False;


x = 2.5

y = 8.2

circle_x = 0;

circle_y = 5;

rad = 2;

if(isInside(circle_x, circle_y, rad, x, y)):

    print(x,y,rad,"Inside");

else:

    print(x,y,rad,"Outside");

1 Answer 1

1

I think it is better to use numpy's vectorization. You can make your function isInside to return a numpy array of boolean values. Then you can just loop outside of the function with a common for-loop. Something like this:

import numpy as np
positions = np.array([[2.5, 8], [3, 10], [0, 5], [1, 5]])
x = positions[:, 0]
y = positions[:, 1]

def isInside(circle_x, circle_y, rad, x, y):
   return ((x - circle_x) ** 2 + (y - circle_y) ** 2) <= rad ** 2

circle_x = 0;
circle_y = 5;
rad = 2;

for is_inside in isInside(circle_x, circle_y, rad, x, y):
  print ("Inside" if is_inside else "Outside")
Sign up to request clarification or add additional context in comments.

2 Comments

but how is it possible to print the respective x and y coordinates also for each individual "Inside" or "Outside"? To get something like : [2.5, 8] Outside, [3, 10] Outside, [0, 5] Inside, [1, 5] Inside?
You can change the for loop so that it has an incremental variable i and then you index the list with this value. For example, first you assign the isInside(...) result to a variable like this is_inside_list = isInside(...) before the for loop, and then change the for to for i in range(len(is_inside_list)). This would iterate i from 0 to lenght of the list. Then you can address inside the values with is_inside_list[i], x[i] and y[i]. Check out this asnwer

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.