I want to assign a number to an internal variable, depending if a specific option has been given, but it seems to fail. Something like:

paropts={a->1, b->2, c->3}

myFunction[t,  opts:OptionsPattern[paropts]]:=

I know the syntax is quite wrong here, but I just want to show the concept. If the option "a" is given then use it to calculate x, otherwise use only 1/t.

That means the function should able to work also if at the beginning my opts are:

paropts={b->2, c->3}

I want to do it as easy as possible and other forms I have tried do not work. I also need to keep the structure of the paropts rules as I have them now, because I use them in many other functions.

It would also be helpful to do it with Block or something else.




I am not sure if I completely understood your problem, but maybe the following is what you are looking for:

myFunction[t_, opts : OptionsPattern[paropts]] := 
 Quiet[With[{x = If[OptionValue[a] =!= a, OptionValue[a]/t, 1/t]}, x + OptionValue[c]]]

It works both when the option a is set, either in paropts or in the function call, or not. I also added an underscore to t.

  • $\begingroup$ Thanks! I think that's the solution, checking if OptionValue does not return the name of the option itself. I think I am safe here, since I use strictly numbers for the options. $\endgroup$ – Santiago Oct 15 '14 at 11:58

Unfortunately your code is too incomplete to test, but the following should do what you want:

myFunction[t, opts:OptionsPattern[paropts]]:=
  With[{x = If[OptionValue[a], a/Optionvalue[b], 1/OptionValue[b]]},
  • $\begingroup$ Hi, thanks for your comment. Yes, I will edit and simplify the function so that it works. But I think your solution is still not working for me. $\endgroup$ – Santiago Oct 15 '14 at 10:41
  • $\begingroup$ I edited my question so that it is a bit more clear! Thanks! $\endgroup$ – Santiago Oct 15 '14 at 10:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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