Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply list to arguments in Mathematica

How would I go about applying each element in a list to each argument in a function? Kind of like Map, except with a variable number of arguments.

So for example, if I have a function action[x1_,x2_,x3_]:=..., and I have a list {1,2,3}, how would I create a function to call action with action[1,2,3]?

I would like this function be able to handle me changing action to action[x1_,x2], and anything else, also, with the list now being {1,2}, and to call action now with action[1,2].

like image 614
wrongusername Avatar asked Apr 21 '11 16:04

wrongusername


People also ask

What is flatten in Mathematica?

Details. Flatten "unravels" lists, effectively just deleting inner braces. Flatten[list,n] effectively flattens the top level in list n times.

Why is evaluate command used in Mathematica?

You can use Evaluate to override HoldFirst etc. attributes of built‐in functions. Evaluate only overrides HoldFirst etc. attributes when it appears directly as the head of the function argument that would otherwise be held. »

What is module in Mathematica?

Module allows you to set up local variables with names that are local to the module. Module creates new symbols to represent each of its local variables every time it is called. Module creates a symbol with name xxx$nnn to represent a local variable with name xxx.


2 Answers

Based on "Kind of like Map, except with a variable number of arguments." I think you might be looking for Apply to level 1. This is done with:

Apply[function, array, {1}]

or the shorthand:

function @@@ array

Here is what it does:

array = {{1, 2, 3}, {a, b, c}, {Pi, Sin, Tan}};

action @@@ array
   {action[1, 2, 3], action[a, b, c], action[Pi, Sin, Tan]}  

The terminology I used above could be misleading, and limits the power of Apply. The expression to which you apply action does not need to be a rectangular array. It does not even need to be a List: {...} or have its elements be lists. Here is an example incorporating these possibilities:

args = {1, 2} | f[a, b, c] | {Pi};

action @@@ args
   action[1, 2] | action[a, b, c] | action[Pi] 
  • args is not a List but a set of Alternatives
  • the number of arguments passed to action varies
  • one of the elements of args has head f

Observe that:

  • action replaces the head of each element of args, whatever it may be.
  • The head of args is preserved in the output, in this case Alternatives (short form: a | b | c)
like image 105
Mr.Wizard Avatar answered Nov 08 '22 03:11

Mr.Wizard


Apply[action, {1,2,3}]

This also can be entered as action @@ {1,2,3}.

like image 9
Sasha Avatar answered Nov 08 '22 02:11

Sasha