# If statement inside a Do loop

• Mathematica
I have a Do loop running which, for some values will become complex, and I want to make it so for these situations, we take the negative root and for others the positive root. In this scenario, I've simplified what I actually have and chose to look at the case where I need it to take the negative root

Code:
Do[e[o] = 0.5 + o, {o, 0, 10}]
Do[If[Element[x[n, o] = (e[o] - n)^(1/2), Complexes], -[x[n, o]],
x[n, o]], {n, -10, 10}, {o, -10, 10}]

I can't seem to get the syntax right here, and if I print a table with the results it's as if the If is just being ignored.
Ideally, this would be the best approach for my problem as my actual code is quite complex and values in the Do loops are called upon, so I fear any other method will cause grief elsewhere.

Thanks for any help!

phyzguy
When you are testing for equality, you need to use ==, not just =. For example If[a==b, step1, step2]

When you are testing for equality, you need to use ==, not just =. For example If[a==b, step1, step2]
I'm not testing for equality here, I have an expression that's defined for different values of n which I need to check if (for some values of n) x[n, o] becomes complex, and when this happens I need it to take the negative value of this.

I have an expression that's defined for different values of n which I need to check

I don't know Mathematica, but I assume debugging strategy should be similar to other languages.

If it's not throwing an error - e.g. if your syntax is correct - then what else might be going on? One thing I might do is put in a statement to print the value being passed to "If"; this way I could see whether the appropriate value appears that ought to trigger the "If". If in fact the appropriate value does appear, that would indicate something else is wrong, maybe inside the "If" statement. In some cases I might pass a static value, or isolate the part of the routine that is problematic by some means, etc. Debugging to me, provided you have the syntax right, is fairly simple-minded; you can use print and other tricks to find out what the code is actually doing, versus what you think it should be doing.

Last edited:
jack action
Gold Member
I'm not fluent in mathematica, but are you sure that x[n, o] = (e[o] - n)^(1/2) returns x[n, o] ? Or does it return a boolean or something like that?

Also, in your first loop, o varies from 0 to 10, then in the 2nd loop it varies from -10 to 10. Where are the missing values of e[o] (from -10 to 0)?

phyzguy