# Defining functions as derivatives

I'm working on a model that requires a sum over a function that uses various coefficients. In order to make the sum easier to perform, I am trying to keep things general through the use of a coefficient array. Consider the set-up:

c={1,2,3,4},
f1[x_,n_]:=x^2*c[[n]]
f2[x_,n_]=D[f1[x,n],x]


I need to be able to define the derivative of f1 as a new function f2. I have two issues. First, I cannot figure out how to specify that c[[n]] is a constant. The second is, I think that Mathematica is evaluating the differential each time f2 is called. It would be better if Mathematica would evaluate the differential and then declare f2 as the resulting derivative.

Note that f2 is not a function declaration using ":=". The result is very different if that notation is used.

How do I specify elements obtained from a given array are constants? Can I evaluate a differential and then declare a function as the differential's result?

• Instead of an array, define c as a function over $1,\dots,4$. c = 1; c = 2; ... May 17, 2016 at 19:21
• Define c as function c[n_?NumericQ] := {1, 2, 3, 4}[[n]] May 17, 2016 at 19:23
• For J.M.'s solution, do ClearAll@c; Evaluate[Array[c, 4]] = {1, 2, 3, 4} and use c[n] instead of c[[n]]. I prefer that one. If you're going to use @swish's answer, I would recommend c[n_Integer] in place of c[n_?NumericQ]. May 17, 2016 at 19:47
• The c[n_Integer] version seems to be working at the moment, more tests to come. How do I make it evaluate the differential once and then simply substitute values in when the function is called? May 17, 2016 at 21:02

First note that with the way you defined f2, the error generated at the time of definition notwithstanding, f2 still works properly.

The scope & context of your problem is not yet clear to me, but if it was me, I would make the code more general by making it more mathematical. Mathematica can usually handle efficiently most problems that can be expressed in terms of multivariable calculus.

Consider the following:

ClearAll[c, f1, f2];
c = {1, 2, 3, 4};
f1[x_] := x^2*c;
f2[x_] = f1'[x] (* or D[f1[x],x] *)
(*
{2 x, 4 x, 6 x, 8 x}
*)


Now f1 and f2 are vector-valued functions. You can perform all the usually algebra & calculus operations on them, including extracting a component f[].