# Declaring a variable array

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.

• Look up Indexed[]. – J. M. will be back soon Sep 7 '17 at 18:00
• 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. – Marius Ladegård Meyer Sep 7 '17 at 18:03
• 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}]]. – march Sep 7 '17 at 18:05
• 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]]] – 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]]
Tanh[h[2]]


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

n=5;
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.