MrD
MrD

Reputation: 5084

Understanding Python Laplacian Implementation

I'm looking at this section of python:

def laplacian(Z):
    Ztop = Z[0:-2,1:-1]
    Zleft = Z[1:-1,0:-2]
    Zbottom = Z[2:,1:-1]
    Zright = Z[1:-1,2:]
    Zcenter = Z[1:-1,1:-1]
    return (Ztop + Zleft + Zbottom + Zright - 4 * Zcenter) / dx**2

Which is supposed to approximate the laplacian of all points on a 2D.

From here

So say I had the grid:

  0  1  2  3  4
0 a  b  c  d  e
1 f  g  h  i  j
2 k  l  m  n  o
3 p  q  r  s  t
4 u  v  w  x  y

The tutorial reads:

We can compute the values of this operator on the grid using vectorized matrix operations. Because of side effects on the edges of the matrix, we need to remove the borders of the grid in the computation.

Ztop includes rows from the start to the second-last, and columns from the second to the last, so it would be:

   1 2 3 4
0  b c d e
1  g h i j
2  l m n o
3  q r s t

Is that right?

The Zcenter includes rows from the second to the last, and columns from the second to the last, so:

   1 2 3 4 
1  g h i j 
2  l m n o 
3  q r s t 
4  v w x y 

Which I guess makes sense, because when we sum Zcenter with Ztop each element in the original grid is summed with the element above.

(Although, shouldn't we then have -2 as end-indexes for Zcenter as we want to exclude the borders?

But then I look at Zbottom, which goes from the third row to the end and from the second column to the last, so:

   1 2 3 4 
2  
3  
4  

So even without filling this in I can see that this grid is 3x4 whereas Zcenter and Ztop are 4x4, so how is the sum possible?

Upvotes: 0

Views: 225

Answers (1)

Chip Grandits
Chip Grandits

Reputation: 357

Ztop chops off the bottom two rows and the first and last column

Zleft chops off the "rightmost" two columns and the first and last row

ZCenter chops off the top and bottom row and "leftmost" and "rightmost" column

Zbottom chops off the top two rows and first and last column

Zright chops off "leftmost" two columns and top and bottom rows.

All generate 3 X 3 if they operate on a 5 X 5

Upvotes: 1

Related Questions