9

Possible Duplicate:
Pass function or formula as function parameter

I am trying to implement a simple Plot[]-like function, with the same synopsis; my first (and unique so far) try would be something along these lines:

MyPlot[f_, {var_, xmin_, xmax_}] := ListPlot[Table[{y, f[y]}, {y, xmin, xmax, (xmax - xmin)/100}]]

however I have to call the function as follows

MyPlot[Sin,{x,0,1}]

while I would prefer calling the function just like Plot[]

MyPlot[Sin[x],{x,0,1}]

I just don't know how to strip the "[x]" when a function is used as an argument to another function. This is not only a matter of consistency with Plot[], it is also needed in order to use a multi-argument function as the argument, such as:

MultiSin[x_,y_]:=Sin[x+y]/(Sqrt[x^2+y^2])
MyPlot[MultiSin[x,1],{x,0,1}]

which is not possible as far as I know with my simple re-implementation.

nilo de roock
  • 9,657
  • 3
  • 35
  • 77
zakk
  • 978
  • 1
  • 7
  • 17

3 Answers3

7
SetAttributes[MyPlot, HoldAll]
MyPlot[f_[a___, var_, b___], {var_, xmin_, xmax_}] := 
      ListPlot[Table[{y, f[a, y, b]}, {y, xmin, xmax, (xmax - xmin)/100}]]

MyPlot[Sin[x], {x, 0, 1}]

Mathematica graphics

MultiSin[x_, y_] := Sin[x + y]/(Sqrt[x^2 + y^2])
MyPlot[MultiSin[x, 1], {x, 0, 1}]

Mathematica graphics

MultiMultiMultiSin[v_, x_, y_, z_] := Sin[x + y] Sin[x y z]/Sin[v]/(Sqrt[x^2 + y^2])
MyPlot[MultiMultiMultiSin[5, x, 2, 5], {x, 0, 1}]

Mathematica graphics

Sjoerd C. de Vries
  • 65,815
  • 14
  • 188
  • 323
3

If you really want the function to work like Plot, it also has to accept arguments that aren't explicitly functions, but simply expressions, such as x^2.

Here's how you do it:

Clear[MyPlot]

SyntaxInformation[MyPlot] = {"LocalVariables" -> {"Plot", {2, 2}}, 
   "ArgumentsPattern" -> {_, _, OptionsPattern[]}};
SetAttributes[MyPlot, HoldAll];

Options[MyPlot] = {};

MyPlot[f_, {x_, xmin_, xmax_}, opts : OptionsPattern[]] := 
 Module[{y, localF},
  localF = f /. x -> y;
  ListPlot[Table[{y, localF},
    {y, xmin, xmax, (xmax - xmin)/100}]
   ]
  ]

MyPlot[Sin[x], {x, 0, 1}]

MyPlot

What I did is to declare the HoldAll attribute so that the expression is passed along unevaluated, and moreover give some syntax information so that you get red typeface if you enter the arguments wrong. Then in the function, I localize the plot variable and call it y instead of the dummy argument x.

Jens
  • 97,245
  • 7
  • 213
  • 499
0

eg

ClearAll[pl];
pl[f_[x_], {x_, llim_, uplim_}] := 
 ListPlot[Table[f[x], {x, llim, uplim}]]

pl[Sin[z], {z, 5, 10}]

or better

ClearAll[pl]
pl[fb___, {x_, llim_, uplim_}] := ListPlot@Table[fb, {x, llim, uplim}]

which also works with

pl[Sin[x + 3], {x, 5, 10}]

and

pl[x^2, {x, 5, 10}]

and so on.

acl
  • 19,834
  • 3
  • 66
  • 91