I'm confused with Mathematica's way of parsing expressions. I've been struggling with this for a while and never found an exhaustive answer, sometimes things don't parse the way I think they would and I don't really understand why.
As an example, with Mathematica 8:
(* A works *)
Manipulate[
Plot[(y/a) /. {y -> (x - b)}, {x, 0, 2}, PlotRange -> {0, 1}],
{a, 1, 2},
{b, 0, 1}]
(* B doesn't work *)
Manipulate[
Plot[(x/a) /. {x -> (x - b)}, {x, 0, 2}, PlotRange -> {0, 1}],
{a, 1, 2},
{b, 0, 1}]
(* C works *)
(x/a) /. {x -> (x - b)}
Manipulate[
Plot[%, {x, 0, 2}, PlotRange -> {0, 1}],
{a, 1, 2},
{b, 0, 1}]
(* D doesn't work *)
test = (x/a) /. {x -> (x - b)}
Manipulate[
Plot[test, {x, 0, 2}, PlotRange -> {0, 1}]
, {a, 1, 2}, {b, 0, 1}]
(* E works *)
test2[x_, a_, b_] = (x/a) /. {x -> (x - b)}
Manipulate[
Plot[test2[x, a, b], {x, 0, 2}, PlotRange -> {0, 1}],
{a, 1, 2},
{b, 0, 1}]
Case A works, so the substitution is performed fine inside Plot and Manipulate.
But B doesn't, which I could understand as an issue trying to substitute a variable with an expression containing itself, but then, if you evaluate it beforehand, as in C, everything works again, so it has to be a problem with x being part of Plot, I guess.
Then if you assign the result of the substitution to a variable, you can't directly plot it, so it seems that variables are not evaluated if they are not functions (as in E, with pattern matching) inside Plot
. But % is, so % is "special" as it gets evaluated inside plot while a standard symbol assigned to a value does not.
Can someone explain me all this? I guess it's related to the Hold
attributes a function can have?
Comments
Post a Comment