I have the following codes:
plotContour[func_,xRange_:{-2,2},yRange_:{-2,2},opts___]:=
ContourPlot[Re[func[x+I*y]],{x,xRange[[1]],xRange[[2]]},{y,yRange[[1]],yRange[[2]]}, opts]
opts
passes the optioanl arguments like ContourStyle
, ImageSize
to the built-in ContourPlot
function. I have provided default argument values to xRange
and yRange
.
But now if I run the following:
plotContour[func,ContourStyle->Red]
I run into problems because it treats ContourStyle->Red
as the arguments xRange
, so I receive errors (Limiting value ContourStyle in ... is not a machine-sized real number.
)
How should I modify the codes so that it works when I provide optional arguments but skip the arguments with default values?
Answer
As already said in a comment, I would not treat what feels more like an option as an usual argument to the function. Instead you can use OptionsPattern
and friends.
For a generic function with both own arguments, and potential arguments supplied to functions used within you can use the following design pattern
Define your own function's options in one of the following fashions
with (protected) symbol (offers the advantage of auto-completion)
Protect[xRange, yRange];
Options[myContourPlot] = {xRange -> {-2, 2}, yRange -> {-2, 2}}with Strings
Options[myContourPlot] = {"xRange" -> {-2, 2}, "yRange" -> {-2, 2}}
And define your function with
myContourPlot[func_, opts : OptionsPattern[{myContourPlot, ContourPlot}]] :=
Module[{x1, x2, y1, y2},
(* read in your options *)
{x1, x2} = OptionValue[xRange] ;
{y1, y2} = OptionValue[yRange];
ContourPlot[Re[func[x + I*y]], {x, x1, x2}, {y, y1, y2},
Evaluate@FilterRules[{opts}, Options@ContourPlot]]]
Now you can call your function with
myContourPlot[Exp, xRange -> {-3, 3}, ContourStyle -> Dashed]
or (depending on your choice concerning symbols or strings as option names)
myContourPlot[Exp, "xRange" -> {-3, 3}, ContourStyle -> Dashed]
Comments
Post a Comment