# Function of an array of values with length dependent on another variable

I need to define a function of arbitrarily many variables, whose number is itself a variable of the function. Schematically it would look as following:

Energia[N_, Array[Theta, N/2, 0]_ ] :=  ...



In such a case I get the error:

Array: Single or list of non-negative machine-sized integers expected at position 2 of Array[Theta,N/2,0].


I guess this is due to the fact that N is undefined inside the function argument. I don't know how to accomodate this need and I have started using Mathematica recently. Do you have an idea on how to fix this problem? Thank you in advance!

• You could put the Condition on the rhs of the definition, something like Energia[n_, Array[t,m,0]]:= ... /;m==n/2. Sep 17, 2021 at 15:36
• Also, N is a reserved symbol. Do not use it as a variable. By the way, did you use an odd integer for N? If so, the second argument of array indeed would not be an integer. Sep 17, 2021 at 15:43
• Thank you for your comments! I corrected the full function definition to: Energia[\[Tau]_, g_ , NN_, L_, Array[\[Theta], s, 0] ] := 1/\[Pi] Sum[(2 \[Pi])/ L (-2 Cos[(2 \[Pi])/L m] + \[Tau]) Cos[\[Theta][m]]^2, {m, 0, NN/2 - 1}] - \[Tau] NN/L - g/\[Pi] Sqrt[ NN/(2 L) - 1/(2 \[Pi]) Sum[(2 \[Pi])/L Cos[\[Theta][m]]^2, {m, 0, N/2 - 1}]] Sum[( 2 \[Pi])/L (2 \[Pi])/L m Sin[2 \[Theta][m]], {m, 0, NN/2 - 1}] /; s == NN/2 but I am still getting that error message. I shared it in case I made a noticeable mistake. Sep 17, 2021 at 15:47

I would suggest something like this. Using a simplified version of the function in the comment:

ClearAll@Energia
Energia[τ_, g_, NN_, L_, vars : {__Theta}] /; Length[vars] == NN/2 := 1/π Sum[
(2 π)/L (-2 Cos[(2 π)/(L m)] + τ) Cos[vars[[m]]]^2,
{m, 1, NN/2}]


Then,

Energia[1, 1, 4, 1, Array[Theta, 2, 0]] // Expand
(* -2 Cos[Theta[0]]^2 + 6 Cos[Theta[1]]^2 *)


and

Energia[1, 1, 4, 1, Array[Theta, 3, 0]] // Expand
(* Energia[1, 1, 4, 1, {Theta[0], Theta[1], Theta[2]}] *)


(i.e., it doesn't evaluate).

I'd prefer the more general version, where you don't have to specify the variable names:

ClearAll@Energia
Energia[τ_, g_, NN_, L_, vars : {__}] /; Length[vars] == NN/2 := 1/π Sum[
(2 π)/L (-2 Cos[(2 π)/(L m)] + τ) Cos[vars[[m]]]^2,
{m, 1, NN/2}]


Then,

Energia[1, 1, 6, 1, {x, y, z}] // Expand
(* -2 Cos[x]^2 + 6 Cos[y]^2 + 4 Cos[z]^2 *)

• This strikes me as an xy problem, though. Sep 17, 2021 at 18:47
• Would you know what the syntax is for the case of two set of variables, i.e., if I need my function to depend on an additional set of variables vars2 with the same length as vars? If I could ask also, would you suggest a good reference to learn Mathematica from the basics, as I feel lost for any such minor modifications? Thanks! Sep 22, 2021 at 15:28