I would like a declare a array h = {h[1], h[2], ..., h[n]} and I would like to keep n general for now. Then I would then like to define a function of this array:

W0[h_] := Sum[log[2*Cosh[h[i]], {1, n}]]

Typically, I would want to later differentiate with respect to say h[1] or something and then set all the h[i] to zero.

  • $\begingroup$ Look up Indexed[]. $\endgroup$ – J. M.'s technical difficulties Sep 7 '17 at 18:00
  • $\begingroup$ You probably don't need a variable array (List in Mathematica) for this. As you see, the code for W0 never references this list, it just uses h[i] directly. But you will need to get specific about n at some point. Mathematica has very limited support for lists of unspecified length. $\endgroup$ – Marius Ladegård Meyer Sep 7 '17 at 18:03
  • $\begingroup$ Note that log should be Log. If you want to keep n general until the time of evaluation, you could instead define W0[h_, n_Integer] := Sum[Log[2*Cosh[h[i]], {1, n}]]. $\endgroup$ – march Sep 7 '17 at 18:05
  • 2
    $\begingroup$ You can make your function work for any length n: W0[h_] := Sum[Log[2*Cosh[h[i]], {1, Length[h]}]] or more simply: W0[h_] := Total[Log[2*Cosh[h]]] $\endgroup$ – bill s Sep 7 '17 at 19:16

Something like this may do what you wish:

n = 5;
hVec = Array[h, 5];
w[hVec_] := Total[Log[2*Cosh[hVec]]];

Now w[hVec] gives:

Log[2 Cosh[h[1]]] + Log[2 Cosh[h[2]]] + Log[2 Cosh[h[3]]] 
    + Log[2 Cosh[h[4]]] + Log[2 Cosh[h[5]]]

For the requested derivative:

D[w[hVec], h[2]]
| improve this answer | |

A minor variation on bill s's approach, which might be useful depending on your needs:

h /: vec[h] := Array[h, n]

w[h_] := Total[Log[2*Cosh[vec@h]]]

Like bill s's approach, this will not deal with arbitrary n.

| improve this answer | |

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.