tags:

views:

368

answers:

2

I have a time-series like function which gives an output based on a list of real numbers(i.e. you can run the function on a list of 1,2,3,... real numbers). The issue I'm encountering is how to maximize the function for a given list length(subject to a set of constraints). I could fix the function to a fixed number of real numbers(i.e. f [x_Real, y_Real] instead of f[x_List]) and treat x and y as the first two elements of the list, and call Maximize on the function, but this is not really elegant. I want to be able to easily change the number of elements in the list.

What is the best way to optimize a function like I described, which takes a list as an argument, for a fixed list length?

A: 

I'm not sure if this is what you're asking, but you can define a function with an unspecified number of inputs with a double underscore:

f[in__] := Mean[{in}]
f[5, 6]
f[1, 2, 3, 4]

Use three underscores to denote zero or more arguments:

g[x_, y_, z___] := {{x}, {y}, {z}}
g[5, 6]
g[1, 2, 3, 4]
Will Robertson
+1  A: 

Use a pure function with a SlotSequence (usually spelled ##) argument, like so:

In[1]:= f = With[{r = Total[{##}^2]}, Sin[r]/r]&;
In[2]:= NMaximize[f[x,y,z], {x,y,z}]
Out[2]= {1., {x -> -0.0000402914, y -> 0.0000278573, z -> -0.0000765568}}

EDIT:

  1. Like ##, xs will be bound to a Sequence, not a List, so Total[xs] won't work. Plus[xs] or Plus[##] would.
  2. I prefer pure functions instead of DownValues for simple things, because they're the simpler construct. Some of this is habit, because in older versions of Mathematica you could get better performance out of pure functions. Using a pure function instead of DownValues is still a good way to indicate that you aren't doing anything fancy with pattern-matching dispatch or non-standard evaluation.
Pillsy
Why not `f[xs___] := With[{r=Total[xs]}, Sin[r]/r]`?
Jon Harrop