1
$\begingroup$

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?

$\endgroup$
  • $\begingroup$ Instead of an array, define c as a function over $1,\dots,4$. c[1] = 1; c[2] = 2; ... $\endgroup$ – J. M. is in limbo May 17 '16 at 19:21
  • 2
    $\begingroup$ Define c as function c[n_?NumericQ] := {1, 2, 3, 4}[[n]] $\endgroup$ – swish May 17 '16 at 19:23
  • 2
    $\begingroup$ 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]. $\endgroup$ – march May 17 '16 at 19:47
  • $\begingroup$ 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? $\endgroup$ – BobJoe1803 May 17 '16 at 21:02
2
$\begingroup$

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[2][[3]].

$\endgroup$

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.