In MATLAB, you can implement that in a simpler way with meshgrid, like so -
Nx = 5;
Ny = 7;
xm_row = -(Nx-1)/2.0+0.5:(Nx-1)/2.0-0.5;
ym_col = (-(Ny-1)/2.0+0.5:(Ny-1)/2.0-0.5)';
[xm_out,ym_out] = meshgrid(xm_row,ym_col)
Let's compare this meshgrid version with the original code for verification -
>> Nx = 5;
>> Ny = 7;
>> xm_row = -(Nx-1)/2.0+0.5:(Nx-1)/2.0-0.5;
>> ym_col = (-(Ny-1)/2.0+0.5:(Ny-1)/2.0-0.5)';
>> xm = xm_row(ones(Ny-1, 1), :)
xm =
-1.5 -0.5 0.5 1.5
-1.5 -0.5 0.5 1.5
-1.5 -0.5 0.5 1.5
-1.5 -0.5 0.5 1.5
-1.5 -0.5 0.5 1.5
-1.5 -0.5 0.5 1.5
>> ym = ym_col(:,ones(Nx-1,1))
ym =
-2.5 -2.5 -2.5 -2.5
-1.5 -1.5 -1.5 -1.5
-0.5 -0.5 -0.5 -0.5
0.5 0.5 0.5 0.5
1.5 1.5 1.5 1.5
2.5 2.5 2.5 2.5
>> [xm_out,ym_out] = meshgrid(xm_row,ym_col)
xm_out =
-1.5 -0.5 0.5 1.5
-1.5 -0.5 0.5 1.5
-1.5 -0.5 0.5 1.5
-1.5 -0.5 0.5 1.5
-1.5 -0.5 0.5 1.5
-1.5 -0.5 0.5 1.5
ym_out =
-2.5 -2.5 -2.5 -2.5
-1.5 -1.5 -1.5 -1.5
-0.5 -0.5 -0.5 -0.5
0.5 0.5 0.5 0.5
1.5 1.5 1.5 1.5
2.5 2.5 2.5 2.5
Now, transitioning from MATLAB to Python has a simpler medium in NumPy, as it hosts many counterparts from MATLAB for use in a Python environment. For our case, we have a NumPy version of meshgrid and that makes it just a straight-forward porting as listed below -
import numpy as np # Import NumPy module
Nx = 5;
Ny = 7;
# Use np.arange that is a colon counterpart in NumPy/Python
xm_row = np.arange(-(Nx-1)/2.0+0.5,(Nx-1)/2.0-0.5+1)
ym_col = np.arange(-(Ny-1)/2.0+0.5,(Ny-1)/2.0-0.5+1)
# Use meshgrid just like in MATLAB
xm,ym = np.meshgrid(xm_row,ym_col)
Output -
In [28]: xm
Out[28]:
array([[-1.5, -0.5, 0.5, 1.5],
[-1.5, -0.5, 0.5, 1.5],
[-1.5, -0.5, 0.5, 1.5],
[-1.5, -0.5, 0.5, 1.5],
[-1.5, -0.5, 0.5, 1.5],
[-1.5, -0.5, 0.5, 1.5]])
In [29]: ym
Out[29]:
array([[-2.5, -2.5, -2.5, -2.5],
[-1.5, -1.5, -1.5, -1.5],
[-0.5, -0.5, -0.5, -0.5],
[ 0.5, 0.5, 0.5, 0.5],
[ 1.5, 1.5, 1.5, 1.5],
[ 2.5, 2.5, 2.5, 2.5]])
Also, please notice that +1 was being added at the end of the second argument to np.arange in both cases, as np.arange excludes the second argument element when creating the range of elements. As an example, if we want to create a range of elements from 3 to 10, we would be required to do np.arange(3,10+1) as shown below -
In [32]: np.arange(3,10+1)
Out[32]: array([ 3, 4, 5, 6, 7, 8, 9, 10])
xis integer - first value from list0..L-1x[ ... ]- this way you expect thatxis a list (array) butxis single number.