Reputation: 24964
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?
Upvotes: 4
Views: 2095
Reputation: 9901
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:
##
, xs
will be bound to a Sequence
, not a List
, so Total[xs]
won't work. Plus[xs]
or Plus[##]
would.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.Upvotes: 3
Reputation: 64520
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]
Upvotes: 1