# Change some option of a function when calling it [duplicate]

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...

## marked as duplicate by Mr.Wizard♦Jul 30 '13 at 6:50

• I think that a general solution applicable to your situation is to create persistent option configurations, for example by using a mechanism I described here. – Leonid Shifrin May 28 '13 at 14:31
• Why not Show[f[1],ImageSize-> 600] ? – andre314 May 28 '13 at 16:04

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]


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


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

• 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

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]


• 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 8:38
• yes, you are right, thanks for your explanation. – Ahmad A May 29 '13 at 9:45