I have sets of functions of material parameters where the first input argument denotes the material. Here's a simple version:

tf1["a", x_] = x^3;
tf1["b", x_] = x^4;


Now, I'd like to make a function which needs the derivative of tf1 with respect to x. My goal is the following:

myderivative["a",x]=3 x^2

myderivative["b",x]=4 x^3

The way to implement this should be something like

myderivative[i_, x_] = Derivative[tf1[i, #] &][x]
myderivativeb[i_, x_] = Derivative[0, 2][tf1][i, x]


I even tried

tf2[i_] = tf1[i, #] &
myderivative2[i_, x_] = Derivative[tf2[i]][x]


But all of the variants return

(tf1^(0,2))[i,x]


I tried using SetDelayed (:=) in all of the above variants but this doesn't return anything else. Also, approaches with D or [Esc] pd [Esc] failed.

So how do I take the derivative of this overloaded function? It should also work with distinct numbers, e.g. I expect

myderivative["a",2]=12

• der[i_, x_] := D[tf1[i, x], x] worked for me? – Pillsy Apr 6 '17 at 16:35
• If tf1 has a first variable, you should define it as: tf1[myname_?String, x_] and define the specific functions for myname = "a" and "b". – David G. Stork Apr 6 '17 at 16:36
• @Pillsy perfect, this seems like the only combination I didn't try... (I was mostly trying pure functions as the argument). Thanks! – riddleculous Apr 6 '17 at 16:39
• @DavidG.Stork this is unrelated to the derivative, but a short example would help me a lot. And maybe a hint why this is better than my way. Thank you very much! – riddleculous Apr 6 '17 at 16:40
• @Pillsy however, your solution doesn't work for der["a",3], for example. There's an error "General::ivar" – riddleculous Apr 6 '17 at 16:50

I suggest doing the derivative and then substituting in a value. This can be done as follows:

der[i_, x_] :=
D[tf1[i, \[FormalX]], \[FormalX]] /. \[FormalX] -> x;


Using a "formal" variable means you don't have to worry about it being defined in scope and screwing things up.

• great! I tried substituting and ReplaceAll but not with the formal variable. Thank you so much! – riddleculous Apr 7 '17 at 8:05
tf1[myname_String, x_] := Which[myname == "a", x^3, myname == "b", x^4];

D[tf1["a", x], x]


(* 3 x^2 *)

D[tf1["b", x], x]


(* 4 x^3 *)

If you have a "default" function for all string variables not yet entered, then:

tf1[myname_String, x_] :=
Which[myname == "a", x^3, myname == "b", x^4, True, Sin[x]];

D[ft1["c",x],x]


(* Cos[x] *)

• since I have many string parameters "a", "b", "c", etc I wanted to save the time of explicitely deriving all of them but wanted to do it as stated in the question (variable i). This is not possible, again giving the error "General::ivar" when putting in values – riddleculous Apr 6 '17 at 16:55
• What is a "question variable"? – David G. Stork Apr 6 '17 at 23:51
• you didn't see the paranthese. Basically, Pillsy's answer is what I was looking for, as it keeps the variable i in the derivative. – riddleculous Apr 7 '17 at 8:08