Re: a question about plot a list of functions.
- To: mathgroup at smc.vnet.net
- Subject: [mg58222] Re: a question about plot a list of functions.
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Thu, 23 Jun 2005 05:34:02 -0400 (EDT)
- Organization: The Open University, Milton Keynes, England
- References: <d9av6m$vn$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Zhou Jiang wrote: > I defined a function as > > K=(2 r/(1-r^2))^2; > y=1/(1+K (Sin[x])^2); > y=y/.{r->{0.2,0.9,0.995}} > > Now the result is a list. > I want to plot y vs. x in one figure and I did the following > > Plot[y, {x, 0, 10 Pi}]; > > But Mathematica gave me an error. > I changed it to > > Plot[{y[[1]], y[[2]], y[[3]]}, {x, 0, 10 Pi}]; > > Mathematica gave me a correct plot. Can anyone give me some idea why the error message is given by Mathematica since y is a list and nothing is diffrent from {y[[1]], y[[2]], y[[3]]}? > > Thanks. > > Hi, Using _Evaluate_ in the plot command will solve your problem: In[1]:= K = (2*(r/(1 - r^2)))^2 Out[1]= (4*r^2)/(1 - r^2)^2 In[2]:= y = 1/(1 + K*Sin[x]^2) Out[2]= 1/(1 + (4*r^2*Sin[x]^2)/(1 - r^2)^2) In[3]:= y = y /. {r -> {0.2, 0.9, 0.995}} Out[3]= {1/(1 + 0.17361111111111113*Sin[x]^2), 1/(1 + 89.75069252077569*Sin[x]^2), 1/(1 + 39799.7500015707*Sin[x]^2)} In[4]:= Plot[Evaluate[y], {x, 0, 10*Pi}]; Why? Although both lists are alike as we can see below In[5]:= {y[[1]], y[[2]], y[[3]]} == y Out[5]= True The _Plot_ command has the attribute _HoldAll_ that tells Mathematica not to evaluate the arguments. In[6]:= Attributes[Plot] Out[6]= {HoldAll, Protected} So in line 4 we force the _Plot_ command to evaluate its arguments that is, in our case, to replace the symbol 'y' by its value which is a list of functions. _Plot_ knows how to deal with a list of functions and the graphs are created. On the other hand, line 7 is interpreted as it is, thus _Plot_ tries to compute some numerical values with the symbol 'y' that has been keept untouched due to the argument _HoldAll_ In[7]:= Plot[y, {x, 0, 10*Pi}]; Plot::plnr: y is not a machine-size real number at x = \ 1.3089969389957471`*^-6. We can see in the error message that Mathematica complains that the symbol 'y' is not a number, which is true in this case since Mathematica never replace 'y' by its value (a list of function that can be numerically evaluated). Best regards, /J.M.