Here are two ways to apply a List of functions to a List of arguments. The first method, from Maeder, uses Inner. Note the use of a purely symbolic example to reveal what Inner is doing.
Inner[#@#2&,{f1,f2,f3,f4},{arg1,arg2,arg3,arg4},List]
{f1[arg1],f2[arg2],f3[arg3],f4[arg4]}
In #1@# &, Slot1 (#1 or abbreviated #) pulls an argument from the first List, which are the functions, and Slot2 (#2 where you do need the "2") pulls an argument from the second List, which are the arguments.
If you wanted to apply a second function, g, to the results rather than just listing them, Inner provides for that:
Inner[#@#2&,{f1,f2,f3,f4},{arg1,arg2,arg3,arg4},g]
g[f1[arg1],f2[arg2],f3[arg3],f4[arg4]]
The second method, from my Mathematica teacher Harry Calkins, uses MapThread, which requires wrapping the function List and the argument List together in a List:
(arguments={{a,b,c},{d,e,f},{r,s,t},{u,v,w}});
(functions={3 #&,3+#&,#/2&,Plus@@@Partition[#,2,1,{1,1},#]&});
He gave an example using some built-in functions and structured the functions and arguments in matrices.By enclosing the assignments in parentheses he showed them as matrices without inadvertently making the assignment to the MatrixForm-formatted List.
arguments//MatrixForm
functions//MatrixForm
(results=MapThread[#1@#2&,{functions,arguments}])//MatrixForm
Inner[#@#2&,{f1,f2,f3,f4},{arg1,arg2,arg3,arg4},List]
{f1[arg1],f2[arg2],f3[arg3],f4[arg4]}
In #1@# &, Slot1 (#1 or abbreviated #) pulls an argument from the first List, which are the functions, and Slot2 (#2 where you do need the "2") pulls an argument from the second List, which are the arguments.
If you wanted to apply a second function, g, to the results rather than just listing them, Inner provides for that:
Inner[#@#2&,{f1,f2,f3,f4},{arg1,arg2,arg3,arg4},g]
g[f1[arg1],f2[arg2],f3[arg3],f4[arg4]]
The second method, from my Mathematica teacher Harry Calkins, uses MapThread, which requires wrapping the function List and the argument List together in a List:
(arguments={{a,b,c},{d,e,f},{r,s,t},{u,v,w}});
(functions={3 #&,3+#&,#/2&,Plus@@@Partition[#,2,1,{1,1},#]&});
He gave an example using some built-in functions and structured the functions and arguments in matrices.By enclosing the assignments in parentheses he showed them as matrices without inadvertently making the assignment to the MatrixForm-formatted List.
arguments//MatrixForm
functions//MatrixForm
(results=MapThread[#1@#2&,{functions,arguments}])//MatrixForm
No comments:
Post a Comment