Plot[2*x^2 - x + 2, {x, -1, 1}] plots a function of x from -1 to 1. As far as I can see, I cannot "save" this range in a variable:
u = {x, -1, 1};
Plot[2*x^2 - x + 2, u]
Generates Plot::pllim: Range specification u is not of the form {x, xmin, xmax}. Hopefully my intention is obvious, what is the most concise way of accomplishing it?
Because someone will wonder why I could possibly want to do this: I have
NDSolve[..., ..., {t, 0, 100}];
Plot[..., {t, 0, 100}];
I don't want to need to modify both 100's as my desired range changes. Yes, I could use variables t0 and t1, but is what type is the range/domain expression? Why can't I store it directly?
Answer
Better methods
My original answer was pretty poor and I'll show you why.
Suppose x has a value assigned: x = 7. This does not bother Plot:
Plot[2*x^2 - x + 2, {x, -1, 1}] (* outputs graphic *)
It however will prevent my earlier suggestions from working:
Plot[2*x^2 - x + 2, Evaluate@u]
During evaluation of In[23]:= Plot::itraw: Raw object 7 cannot be used as an iterator. >>
Plot[2 x^2 - x + 2, {7, -1, 1}]
Instead you should store your range in a way that holds the plot parameter unevaluated:
u = Hold[{x, -1, 1}];
Then you need a way to put this inside the Plot expression without it evaluating. This can be done with a Function and a hold attribute and Apply:
Function[spec, Plot[2*x^2 - x + 2, spec], HoldAll] @@ u (* outputs graphic *)
Or more tersely with the "injector pattern":
u /. _[spec_] :> Plot[2*x^2 - x + 2, spec] (* outputs graphic *)
Old answer
You just need Evaluate:
u = {x, -1, 1};
Plot[2*x^2 - x + 2, Evaluate @ u]

Or as I often prefer, Function:
Plot[2*x^2 - x + 2, #] & @ u
Comments
Post a Comment