Question

Solving a complicated formula f(u,v)==0, where

I assign some constant value to u and then solve v.

I can solve it without for-loop, but encounter errors by adding For[] enclosing the codes,

where saying

Set::write: Tag Times in "Solve[] with exact coefficients solns is Protected.

A simple example to illustrate my idea:

  For[  i = 1, i < 5, i++,

        f = x^2 + y^2 - 10;
        x = i;
        eqn = (f == 0);
        soln = Solve[eqn, y]

     ]

will get error:

Set::write: "Tag Times in (-9+y^2) is Protected."

Only when I add For[ ] at the outside of the code

(inner 4-line code works fine without for loop)

So it seems that there is an variable assignment permission issue in the for loop

How can I avoid it?

Was it helpful?

Solution

I no longer have Mathematica 7 installed, and your code runs (although with no printed output...) on Mathematica 10. Based on the error message, it sounds like you need to Clear[f] before trying to reassign it.

For[i = 1, i < 5, i++,
 Clear[f];
 f = x^2 + y^2 - 10;
 x = i;
 eqn = (f == 0);
 soln = Solve[eqn, y];
 Print[soln]
]

However, you're still really mixing things up. Consider what happens with your code as the loop executes. First it starts with i=1 and says:

  • Clear[f] -- or don't, this isn't the only issue
  • f = x^2 + y^2 - 10 -- This gives me an expression with symbols x and y
  • x=i -- This sets x=1 since i=1 already

At this point, the expression for f has become y^2 - 9`. Next time it comes around, it will repeat:

  • f = x^2 + y^2 - 10 -- But x is no longer a symbol!! So now it still treats x=1...

This becomes a nightmare. I could try to hack your code into working with the fewest changes (e.g. make it Clear[f,x] or something), but that's not really the best advice I can give.

A better overall construction would be something like:

Eqn[x_,y_]=(x^2+y^2-10==0);
For[i=1,i<5,i++,
 Print[Solve[Eqn[i,y],y]];
];

Your function f is a function, so you should make it a function like f[x_,y_]=something. Better yet, just make the entire equation into a function as above. That way, you never actually modify the values of x or y and don't get caught with issues in your loop.

And before you use this new code I've given you, clear everything or just quit the Kernel.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top