David Rinck
David Rinck

Reputation: 6996

Meshgrid and confusion regarding X and Y coordinates

import numpy as np
def L2Norm(f, x, y, d=0.00001):
    dudx = (f(x+d,y) - f(x-d,y)) / (2*d) 
    dudy = (f(x,y+d) - f(x,y-d)) / (2*d)
    L2Norm = np.float128(np.sqrt(dudx**2 + dudy**2))
return L2Norm

def f(x,y):
    return np.float128((1.0 + np.sin(np.pi*x))*((3.0 + np.cos(2.011*y))**2)*np.e**((-x**2)-((y**2)/4)))

# 20 points in X direction
x = np.linspace(-1.0,1.0,20)
# 40 points in Y direction
y = np.linspace(-2.0,2.0,40)
[X,Y] = np.meshgrid(x,y)
L2_Norm = L2Norm(f, X, Y)
print L2_Norm[37,13]

My function is above. Basically, I would expect to call the function L2Norm and get an array going from 0 to 19 in the X direction, or first index and 0 to 39 in the second.

Instead, it seems like the first index now corresponds to where I would expect y to be.

I can call L2_Norm[39,19] but not L2_Norm[19,39] Why is this?

Upvotes: 0

Views: 1316

Answers (1)

JoshAdel
JoshAdel

Reputation: 68752

If you call L2_Norm.shape, you'll see that the dimensions of the array is (40,20) so as the error states, L2_Norm[19,39] is out of range because 39 > the max index in that dimension of 19. Take a look at the shape of X and Y as well to see why L2_Norm has the shape that it does -- the reason is clear if you look in the meshgrid documentation:

For vectors x, y with lengths Nx=len(x) and Ny=len(y), return X, Y where X and Y are (Ny, Nx) shaped arrays with the elements of x and y repeated to fill the matrix along the first dimension for x, the second for y.

Upvotes: 2

Related Questions