Martina Cotti
Martina Cotti

Reputation: 11

Make a better grid of points with python

I can make simple grid of points in a rectangular domain by simply saying:

import numpy as np

x = np.linspace(0,2,M+1)
y = np.linspace(0,1,N+1)
X,Y = np.meshgrid(x,y)

And put this value in a particular order that I want (I want the code to read through the points along the x and then shift to the following y)

positions = np.vstack([Y.ravel(), X.ravel()])

Now, i need my code to distinguish between perimeter points and internal points of the grid and be able to call them easily, because my function has know values on those points. How can this be done?

Upvotes: 1

Views: 7345

Answers (1)

MB-F
MB-F

Reputation: 23637

The perimeter of a rectangular axis-aligned grid consists of all the points where either coordinate is most extreme.

Simply put, find all positions where x and y are either maximum and minimum:

is_perimeter = (positions[0] == np.min(y)) | (positions[0] == np.max(y)) | (positions[1] == np.min(x)) | (positions[1] == np.max(x))

For any point i is_perimeter[i] is True if the corresponding point positions[:, i] is on the perimeter, and it is False otherwise.

Let's verify the result:

import numpy as np
import matplotlib.pyplot as plt

M, N = 5, 8

x = np.linspace(0,2,M+1)
y = np.linspace(0,1,N+1)
X,Y = np.meshgrid(x,y)

positions = np.vstack([Y.ravel(), X.ravel()])

is_perimeter = (positions[0] == np.min(y)) | (positions[0] == np.max(y)) | \
               (positions[1] == np.min(x)) | (positions[1] == np.max(x))

plt.scatter(*positions[::-1], c=is_perimeter)
plt.show()

enter image description here

Upvotes: 1

Related Questions