# Having problem with using Replace in Do-loop

I am trying to set to zero some expression in a very long summation in mathematica. So I have decided to use a do loop along with a the replace operator over all indices I want to remove (actually indices such as [-i, 0], [0,0] and [i, 0]).

Do[
Cor = Cor /. {q[i, 0] -> 0}
, {i, 0, ndof1}]
Cor


with Cor is something like

Cor = - Sum[ (eps[j, k]*q[j, k]     +
q[j, k]*abs (q[j, k])^(sig) -
w*(q[j - 1, k] + q[j + 1, k] + q[j, k - 1] + q[j, k + 1]) )^2
, {j, 0, ndof1}, {k , 0, ndof2}]


As a result, I am getting something with

/. 0 /. 0 /. 0 /. 0 /. 0 /. 0 /. 0 /. 0 /. 0 /. 0 /. 0


at the end on which I can't perform further operation like derivative for instance.

Please can someone help. I am struggling with this problem in many of my codes so that I get a proper expression at the end.

• can you explicitly define the variable q like Do[q[i,0]=0, {i, 0, ndof1}]? and then evaluate Cor? – Sumit Jul 12 '17 at 10:45
• You can use rep = Table[q[i, 0] -> 0, {i, 0, n1}] and then cor /. rep – eldo Jul 12 '17 at 10:51
• Thanks you, I have tried it in many cases it works fine. – many Jul 12 '17 at 13:30

You can use ReplaceAll on the expression Cor to achieve your goal.

Let's try a test case

ndof1 = 2;
ndof2 = 1;
sig = 2;


Evaluate Cor

Cor = -Sum[(eps[j, k]*q[j, k] + q[j, k] abs (q[j, k])^(sig) -
w*(q[j - 1, k] + q[j + 1, k] + q[j, k - 1] +
q[j, k + 1]))^2, {j, 0, ndof1}, {k, 0, ndof2}]

(* -(eps[0, 0] q[0, 0] + abs q[0, 0]^3 -
w (q[-1, 0] + q[0, -1] + q[0, 1] + q[1, 0]))^2 - (eps[0, 1] q[0,
1] + abs q[0, 1]^3 -
w (q[-1, 1] + q[0, 0] + q[0, 2] + q[1, 1]))^2 - (eps[1, 0] q[1,
0] + abs q[1, 0]^3 -
w (q[0, 0] + q[1, -1] + q[1, 1] + q[2, 0]))^2 - (eps[1, 1] q[1,
1] + abs q[1, 1]^3 -
w (q[0, 1] + q[1, 0] + q[1, 2] + q[2, 1]))^2 - (eps[2, 0] q[2, 0] +
abs q[2, 0]^3 -
w (q[1, 0] + q[2, -1] + q[2, 1] + q[3, 0]))^2 - (eps[2, 1] q[2,
1] + abs q[2, 1]^3 - w (q[1, 1] + q[2, 0] + q[2, 2] + q[3, 1]))^2 *)


Use ReplaceAll on the Cor expression

corNew = Cor /. q[_, 0] -> 0

(* -w^2 (q[0, -1] + q[0, 1])^2 -
w^2 (q[1, -1] + q[1, 1])^2 - (eps[0, 1] q[0, 1] + abs q[0, 1]^3 -
w (q[-1, 1] + q[0, 2] + q[1, 1]))^2 -
w^2 (q[2, -1] + q[2, 1])^2 - (eps[1, 1] q[1, 1] + abs q[1, 1]^3 -
w (q[0, 1] + q[1, 2] + q[2, 1]))^2 - (eps[2, 1] q[2, 1] +
abs q[2, 1]^3 - w (q[1, 1] + q[2, 2] + q[3, 1]))^2 *)

• This also works fine. Thanks guys. – many Jul 15 '17 at 11:11