# Replace some terms in a long sum with non zero values [Using Do loop]

I am facing a problem performing replacement of certain terms of a long sum by non zero values. I have posted a similar question ( Having problem with using Replace in Do-loop) but I was trying to replace with zero the out of bound terms. Well the sum is

BM = 0;
For[ i = 1, i <= ndof1, i++,
For[ j = 1, j <= ndof2, j++,
If[ Mod[ i + j, 2] == 0,
BM = BM +
VM[u[i, j, 1], u[i, j, 2], u[i, j + 1, 1], u[i, j + 1, 2]] +
VM[u[i, j, 1], u[i, j, 2], u[i - 1, j, 1], u[i - 1, j, 2]] +
VM[ u[i, j, 1], u[i, j, 2], u[i, j - 1, 1], u[i,  j - 1, 2]];
Print[ "In even : " <> ToString[i + j]] ;(*
Check the way the code is taking the sum *)
]
If[ Mod[ i + j, 2] == 1,
BM = BM +
VM[u[i, j, 1], u[i, j, 2], u[i, j + 1, 1], u[i, j + 1, 2]] +
VM[u[i, j, 1], u[i, j, 2], u[i + 1, j, 1], u[i + 1, j, 2]] +
VM[ u[i, j, 1], u[i, j, 2], u[i, j - 1, 1], u[i,  j - 1, 2]];
Print[ "In odd : " <> ToString[i + j]] ; (*
Check the way the code is taking the sum *)
]
]
]
BM = BM /2;


Where VM is a function defined on this way:

r[x1_ , y1_ , x2_ , y2_] := Sqrt[(x2 - x1)^2 + (y2 - y1)^2]
VM[xi_, yi_, xo_, yo_] := D*(Exp[-a* (r[xi, yi, xo, yo]     -  r0)] -
1)^2'


I want to replace out of bound terms with in in-bound terms for instance u[i, 0, 1] -> u[i, ndof2, 1] (periodic boundaries conditions)

Hence, I do in my code (for instance)

Do[ u[i, 0, 1] = u[i, ndof2, 1], {i, -ndof1, ndof1 + 1}]
ruleIO1 = Table[u[i, 0, 1] -> u[i, ndof2, 1], {i, -ndof1, ndof1 + 1}]
BMNew = BM /. ruleIO1;


which seems to work fine. But when I perform the derivative of BMNew with respect to one of the removed variables says D[BMNew, u[5, 0, 1]]

I get a result!!!! Meaning that I don't do it properly.

Can some one help me to do it properly.

Thanks

Clear[BMorse]; BMorse = BM; (* Running along x on boundaries*) Do [ BMorse = BMorse /. u[i, 0, 1] -> u[i, ndof2, 1]; BMorse = BMorse /. u[i, 0, 2] -> u[i, ndof2, 2]; BMorse = BMorse /. u[i, ndof2 + 1, 1] -> u[i, 1, 1]; BMorse = BMorse /. u[i, ndof2 + 1, 2] -> u[i, 1, 2]; , {i, 0, ndof1}] (* Running along y on boundaries *) Do[ BMorse = BMorse /. u[0, j, 1] -> u[ndof1, j, 1]; BMorse = BMorse /. u[0, j, 2] -> u[ndof1, j, 2]; BMorse = BMorse /. u[ndof1 + 1, j, 1] -> u[1, j, 1]; BMorse = BMorse /. u[ndof1 + 1, j, 2] -> u[1, j, 2]; , {j, 0, ndof2}]