Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

The following made me curious. Suppose you want to sum the if statement If[x[i] < 1., x[i]^2, 0.] over i=1,2, i.e.

Sum[If[x[i] < 1., x[i]^2, 0.], {i, 1, 2}]. 

Mathematica returns

If[x[1] < 1., x[i]^2, 0.] + If[x[2] < 1., x[i]^2, 0.].

Notice the i's if the statement is true. However, I thought a more "natural" representation of the sum should look like

If[x[1] < 1., x[1]^2, 0.] + If[x[2] < 1., x[2]^2, 0.].

Does anybody can enlighten me on this one? Thanks in advance.

share|improve this question
    
Try Sum[If[x[i] < 1., 1/0, 0^0], {i, 1, 2}]. –  b.gatessucks Feb 14 '13 at 10:11
    
Related: mathematica.stackexchange.com/q/7756/121 –  Mr.Wizard Feb 22 '13 at 7:47

1 Answer 1

Since If has attribute HoldRest, the i will not be inserted into the latter parts during the evaluation. Consider this example showing the same effect:

Sum[s[i, Hold[i]], {i, 1, 2}]
(* s[1, Hold[i]] + s[2, Hold[i]] *)

I think the best practices way of getting what you are asking for is to use With to ensure i gets inserted:

Sum[With[{i = i}, If[x[i] < 1., x[i]^2, 0]], {i, 1, 2}]
(* If[x[1] < 1., x[1]^2, 0] + If[x[2] < 1., x[2]^2, 0] *)
share|improve this answer
    
Thanks, I really appreciate your help. –  chris Feb 14 '13 at 10:26

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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