3
$\begingroup$

Suppose I need to write a function to plot the real and imaginary part of some function (just an example). I want to define a function foo so that foo[f[t],{t,0,10},PlotRange->All,(some other plot options)] essentially calls

Plot[{Re[f[t]],Im[f[t]]},{t,0,10},PlotRange->All,(some other plot options)]

How to achieve that with, say, pattern matching?

$\endgroup$
5
  • $\begingroup$ Does this give what you need: ClearAll[foo]; SetAttributes[foo, HoldFirst]; foo[f_[t_], {t_, tmin_, tmax_}, opts : OptionsPattern[]] := Plot[{Re[f[t]], Im[f[t]]}, {t, tmin, tmax}, PlotRange -> All, opts]? $\endgroup$
    – kglr
    Jan 6, 2015 at 2:39
  • 2
    $\begingroup$ ... or foo2 = Plot[{Re[#], Im[#]}, #2, PlotRange -> All, ##3] &;? $\endgroup$
    – kglr
    Jan 6, 2015 at 2:44
  • $\begingroup$ @kguler thanks, but foo[Sin[t] + I*Cos[t], {t, 0, 10}, PlotRange -> All] does not work on my machine (output is exactly "foo[Sin[t] + I*Cos[t], {t, 0, 10}, PlotRange -> All]"). $\endgroup$ Jan 6, 2015 at 2:46
  • $\begingroup$ @kguler foo2 works perfectly. $\endgroup$ Jan 6, 2015 at 2:48
  • 1
    $\begingroup$ @kguler The foo definition given by @kguler will actually work if you just replace {Re[f[t]], Im[f[t]]} with Evaluate@{Re[f[t]], Im[f[t]]}. These comments should be posted as an answer ;) $\endgroup$
    – SquareOne
    Jan 9, 2015 at 11:03

2 Answers 2

3
$\begingroup$

I propose this:

SetAttributes[myPlot, HoldAll]

myPlot[x_, args__, opts : OptionsPattern[Plot]] := 
  Plot[{Re@x, Im@x}, args, opts, PlotRange -> All]

Test:

myPlot[Sin[t] + I*Cos[t], {t, 0, 10}]

enter image description here

  • HoldAll is used to mimic the evaluation behavior of Plot.

  • OptionsPattern[Plot] is used to define the valid options as being those of Plot.

  • opts is placed before PlotRange -> All so that an explicit PlotRange will overrule the default; this is usually desired.

For a longer example of option customization please see:

Also related:

$\endgroup$
1
$\begingroup$
ClearAll[foo];
foo = Plot[{Re[#], Im[#]}, #2, PlotRange -> All, ##3] &;

foo[Sin[t] + I*Cos[t], {t, 0, 10}, PlotStyle -> Thick]

enter image description here

$\endgroup$
1
  • 1
    $\begingroup$ This is terse, and you know I like terse, but there is a problem with it as-written: you lose the HoldAll behavior of Plot so this will break if e.g. t has a global value. $\endgroup$
    – Mr.Wizard
    Jan 22, 2015 at 18:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.