1
$\begingroup$

Suppose I have a function that depends on variables $x_1, ... , x_n$. For concreteness I may have $f(x) = v \cdot x$, with $v$ a certain vector.

Now I want to do certain operation with this function, for example to compute its gradient.

I would like to write a mathematica code that works for any n. Thus, I cannot write something like

f[x1_,...,xn_]:= (any clever way to write v . x);

because that would not work for another n: I have to manually write the new simbols x1,...,xn'.

Also, the following would not work:

f[x_]:= v . x;

because then I would not be able to use Derivative, as f is now a function of a single argument (a list), and it is impossible to get the derivative with respect to x[[2]] say. (Right?)

What is the best design to work with this kind of problems?

$\endgroup$
  • 1
    $\begingroup$ ClearAll[f]; f[x__] := v.{x}? $\endgroup$ – kglr Sep 9 '17 at 12:30
  • 1
    $\begingroup$ A related question. $\endgroup$ – J. M. will be back soon Sep 9 '17 at 12:30
  • 3
    $\begingroup$ Of course Mathematica functions can have an arbitrary number of arguments. But why not just let the function take a list, which is treated as a single argument? f[list_List]:=Total[list]. Using the multi-argument notation, this would be f[x___]:=Total[{x}]. Here I put x between curly braces again to make a list out of it. So it's really the same thing as a function taking a list-argument. The difference is only notation, nothing else. This should make it easier for you to think about the problem. $\endgroup$ – Szabolcs Sep 9 '17 at 12:56
  • $\begingroup$ But how would you compute the derivative with respect to the i-th argument? $\endgroup$ – giulio bullsaver Sep 9 '17 at 14:14
  • $\begingroup$ D was enhanced in V11.1 to help with this sort of problem. Take a look at this Wolfram Blog article $\endgroup$ – m_goldberg Sep 9 '17 at 18:13

Your Answer

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

Browse other questions tagged or ask your own question.