7

Say I have defined some function like

f[p_] := Plot[Sin[p*x], {x, 0, 2 Pi}]

Now in most cases, I just need to specify the value of p and retrieve the plot. In a very few cases, I also want to change some option of the plot, e.g. ImageSize -> Large.

Since my function in reality is a lot more convoluted and already has various optional arguments, I am trying to avoid a solution like

f[p_, size_:Automatic] := Plot[Sin[p*x], {x, 0, 2 Pi}, ImageSize->size]

I have tried e.g.

f[*some value*] /. ImageSize -> Large

but to no avail. Is there any way to achieve what I am attempting? Apologies if I am missing some fundamental features of Mathematica...

Bernd
  • 965
  • 9
  • 19

2 Answers2

6

You can use functions with optional arguments

For example:

ClearAll@f;
Options[f] = Options[Plot];

f[p_, opt : OptionsPattern[]] := Plot[Sin[p*x], {x, 0, 2 Pi}, opt]

f[3]

default

f[3, PlotStyle -> {Red, Thick}, ImageSize -> Small]

Options passed

For completeness sake: you can define your function to accept other options (not just those of Plot). In that case you can use FilterRules.

Ajasja
  • 13,634
  • 2
  • 46
  • 104
  • Thanks, but as mentioned in my question, the function already has a few optional arguments so I am trying to avoid adding another one which I'd use only once - since at some point it gets confusing which option actually IS used in a specific case (take f[x_, opt1_:, opt2_:, opt_3]:=... and the use f[1, *some specification*]). – Bernd May 28 '13 at 14:41
  • @Bernd see edit. I would concatenate all your optional parameters to Options. If you elaborate your example I can show you how I would solve it. – Ajasja May 28 '13 at 14:43
  • I'm sorry, I didn't realise the difference between an optional argument (opt_:) and your use of OptionsPattern (opt:), which I hadn't known of. That should do the trick, thanks! – Bernd May 28 '13 at 14:53
  • @Bernd You're welcome:) – Ajasja May 28 '13 at 14:55
1

A simpler form of Ajasja's idea can be used:

f[p_, opt : ___] := Plot[Sin[p*x], {x, 0, 2 Pi}, opt]

f[3, PlotStyle -> {Red, Thick}, ImageSize -> Small]

enter image description here

Ahmad A
  • 363
  • 1
  • 8
  • 3
    This is similar to how old-style options handling used to be done. But it has several drawbacks: You can't get a list of all excepted options of f, it matches everything, not just a sequence of rules, you can't use OptionValue[]. Of course for this particular purpose it might suffice. – Ajasja May 29 '13 at 08:38
  • yes, you are right, thanks for your explanation. – Ahmad A May 29 '13 at 09:45