2
$\begingroup$

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.

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

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 *)
$\endgroup$
  • $\begingroup$ This also works fine. Thanks guys. $\endgroup$ – many Jul 15 '17 at 11:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.