I have a list of functions
func[x_]={1,Cos[x],Sin[x]}
(for example) and I want to apply each function to a list of values
xval={a,b,c,d}
obtaining a list of tuples. The problem is that the constant function will not evaluate to a tuple (it will remain as a scalar)
func[xval] = {1, {0, -1, 0, 1}, {1, 0, -1, 0}}
Is there a way to force the creation of a tuple (with the function value) of the same size as xval
, if I don't know what are the functions in func
(if there is or not a constant function in it)?
Answer
The reason why it works with Cos
and Sin
is that those functions are Listable
. So just make a constant function that is Listable, too:
func[x_]:={Function[y, 1, Listable][x],Cos[x],Sin[x]}
xval={a, b, c, d}
func[xval]
(*
==> {{1, 1, 1, 1}, {Cos[a], Cos[b], Cos[c], Cos[d]},
{Sin[a], Sin[b], Sin[c], Sin[d]}}
*)
Note that here it is important that you use :=
to define func
, otherwise it gets evaluated already at definition time, resulting in a single 1
again.
If you need it often, you can define a function to generate a listable constant function:
const[x_] := Function[y, x, Listable]
Then you can write:
func2[x_] := { const[1][x], Cos[x], Sin[x] }
func2[xval]
(*
==> {{1, 1, 1, 1}, {Cos[a], Cos[b], Cos[c], Cos[d]},
{Sin[a], Sin[b], Sin[c], Sin[d]}}
*)
Comments
Post a Comment