- #1
jackmell
- 1,807
- 54
Hi. I've been working on a finite-difference problem in differential equations. I was wondering if this code can be further optimized, perhaps eliminate some if statements or assignment statements. That is, what is the most efficient way to code this or is it already written in the most efficient way? It goes through the matrix u(0..M-1, 0. .N-1) and for each u(i,j), computes:
u(i,j+1)-2u(i,j)+u(i,j-1)+u(i+1,j)-2u(i,j)+u(i-1,j)
except that when it gets to the end, it wraps around to the start and likewise when it's at the start, it wraps around to the end so that:
if i=0, then i-1 goes to M-1
if i=M-1, then i+1 goes to 0
if j=0, then j-1 goes to N-1
if j=N-1, then j+1 goes to 0
Here's the code taken from:
http://www.teemuleppanen.net/content/science/turing/turing_learning.shtml
u(i,j+1)-2u(i,j)+u(i,j-1)+u(i+1,j)-2u(i,j)+u(i-1,j)
except that when it gets to the end, it wraps around to the start and likewise when it's at the start, it wraps around to the end so that:
if i=0, then i-1 goes to M-1
if i=M-1, then i+1 goes to 0
if j=0, then j-1 goes to N-1
if j=N-1, then j+1 goes to 0
Here's the code taken from:
http://www.teemuleppanen.net/content/science/turing/turing_learning.shtml
Code:
for(i=0;i<M;i++)
for(j=0;j<N;j++){
lap[i][j] = 0;
if(j!=N-1)
lap[i][j] += u[i][j+1]-u[i][j];
if(j!=0)
lap[i][j] += u[i][j-1]-u[i][j];
if(i!=0)
lap[i][j] += u[i-1][j]-u[i][j];
if(i!=M-1)
lap[i][j] += u[i+1][j]-u[i][j];
if(j==N-1)
lap[i][j] += u[i][0]-u[i][j];
if(j==0)
lap[i][j] += u[i][N-1]-u[i][j];
if(i==M-1)
lap[i][j] += u[0][j]-u[i][j];
if(i==0)
lap[i][j] += u[M-1][j]-u[i][j];
lap[i][j] = lap[i][j]/(dx*dx);
}
Last edited: